package com.quanyan.place.wrapper.impl;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.ApiResponseEnum;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.enums.PlatformTypeEnum;
import com.quanyan.common.enums.SysParameterConfigEnum;
import com.quanyan.common.utils.CommonUtils;
import com.quanyan.common.utils.DateTimeUtils;
import com.quanyan.common.utils.DateUtils;
import com.quanyan.common.utils.UUIDUtils;
import com.quanyan.place.biz.ISearchService;
import com.quanyan.place.cache.PlaceRedisTemplate;
import com.quanyan.place.component.MerchantClientPayType;
import com.quanyan.place.constants.PlaceConstants;
import com.quanyan.place.entity.TbAdminUser;
import com.quanyan.place.entity.TbBizPlace;
import com.quanyan.place.entity.TbBizPlaceAttach;
import com.quanyan.place.entity.TbBizPlaceCategory;
import com.quanyan.place.entity.TbBizPlaceMember;
import com.quanyan.place.entity.TbBizPlaceMemberCard;
import com.quanyan.place.entity.TbBizPlaceMemberCardType;
import com.quanyan.place.entity.TbBizPlaceMemberCardTypeExample;
import com.quanyan.place.entity.TbBizPlaceMemberOpHistory;
import com.quanyan.place.entity.TbBizPlaceOrder;
import com.quanyan.place.entity.TbCommonParameter;
import com.quanyan.place.entity.apireq.ReqAdjustMemberBalance;
import com.quanyan.place.entity.apireq.ReqMemberCard;
import com.quanyan.place.entity.apireq.ReqMemberCardType;
import com.quanyan.place.entity.apireq.ReqMemberCards;
import com.quanyan.place.entity.apireq.ReqOrderHistory;
import com.quanyan.place.entity.apireq.ReqOrderOperate;
import com.quanyan.place.entity.apiresp.RespCardPayList;
import com.quanyan.place.entity.apiresp.RespMemberCardInfo;
import com.quanyan.place.entity.apiresp.RespMemberCardType;
import com.quanyan.place.entity.apiresp.RespPayInfo;
import com.quanyan.place.entity.apiresp.RespPlaceInfo;
import com.quanyan.place.entity.apiresp.RespPlaceMemberCardDetail;
import com.quanyan.place.entity.vo.PlaceFinanceAuditVo;
import com.quanyan.place.entity.vo.PlaceMemberTypeVo;
import com.quanyan.place.entity.vo.PlacePrintVo;
import com.quanyan.place.entity.vo.PlaceScanOrderPayVo;
import com.quanyan.place.entity.vo.ReqPlaceMemberSearch;
import com.quanyan.place.enums.PayTypeEnum;
import com.quanyan.place.enums.PlaceCategoryEnum;
import com.quanyan.place.mapper.TbBizPlaceMapper;
import com.quanyan.place.mapper.TbBizPlaceMemberCardTypeMapper;
import com.quanyan.place.service.AdminUserService;
import com.quanyan.place.service.BaseService;
import com.quanyan.place.service.FinanceService;
import com.quanyan.place.service.PlaceBaseService;
import com.quanyan.place.service.PlaceMemberService;
import com.quanyan.place.service.PlaceOrderService;
import com.quanyan.place.service.PlaceOrderUtilService;
import com.quanyan.place.service.PlaceTicketService;
import com.quanyan.place.service.TbBusinessLogService;
import com.quanyan.place.service.impl.CardNoServiceImpl;
import com.quanyan.place.wrapper.PlaceMemberWrapper;
import com.quanyan.sms.service.SmsService;
import com.quanyan.user.request.ReqBackstageUser;
import com.quanyan.user.request.ReqChangePhone;
import com.quanyan.user.response.RespUserInfoBase;
import com.quanyan.user.serviceFacade.UserServiceFacade;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import sms.SmsApi;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 场馆会员wrapper实现
 * Created by yangyun on 16-8-25.
 */
@Service("placeMemberWrapper")
public class PlaceMemberWrapperImpl implements PlaceMemberWrapper{
    private static final Logger logger = LoggerFactory.getLogger(PlaceMemberWrapperImpl.class);

    @Autowired
    PlaceMemberService placeMemberService;

    @Autowired
    UserServiceFacade userServiceFacade;

    @Autowired
    CardNoServiceImpl cardNoService;

    @Autowired
    TbBusinessLogService businessLogService;

    @Autowired
    SmsService smsService;

    @Autowired
    BaseService  baseService;

    @Autowired
    PlaceBaseService placeBaseService;

    @Autowired
    PlaceTicketService placeTicketService;

    @Autowired
    PlaceOrderService placeOrderService;

    @Autowired
    ISearchService searchService;
    @Autowired
    TbBizPlaceMemberCardTypeMapper tbBizPlaceMemberCardTypeMapper;
    @Autowired
    PlaceOrderUtilService placeOrderUtilService;
    @Autowired
    com.quanyan.place.biz.SmsService  placeSmsService;
    @Autowired
    TbBizPlaceMapper tbBizPlaceMapper;

    @Autowired
    PlaceRedisTemplate placeRedisTemplate;
    @Autowired
    FinanceService financeService;

    @Autowired
    AdminUserService AdminUserService;

    /**
     * 增加会员卡类型
     * @param reqMemberCardType
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse insertMemberType(ReqMemberCardType reqMemberCardType) throws Exception{
        APIResponse apiResponse = placeMemberService.insertMemberType(reqMemberCardType);
        // 将场馆is_vip更新
        if (reqMemberCardType.getSourceType() != PlaceConstants.PLACE_MEMBER_CARD_TYPE_BARGAINING_MEMBER){
            TbBizPlaceAttach placeAttach = placeBaseService.getBizPlaceAttach(reqMemberCardType.getPlaceId());
            boolean flag = false;
            if (placeAttach!=null){
                if (null == placeAttach.getIsVip() || Constants.BYTE_ZERO == placeAttach.getIsVip()){
                    placeAttach.setIsVip(Constants.BYTE_ONE); // 支持办理会员卡
                    placeBaseService.updatePlaceAttachBySelective(placeAttach);

                    //是否支持会员存放到redis
                    String placeIdKey = PlaceConstants.CACHE_PLACE_ATTACH_INFO_PREFIX+String.valueOf(placeAttach.getPlaceId());
                    placeRedisTemplate.set(placeIdKey,placeAttach,PlaceConstants.PLACE_INFO_CACHE_TIME);

                    flag = true;
                }
                if (flag){
                    searchService.addPlaceSaleIndex(reqMemberCardType.getPlaceId());
                }
            }
        }
        return apiResponse;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse<?> cardRechargeForScanPay(Map map, Integer cardID, Integer createUid, Integer adminPayType,  Double dAmount,
                                          Double dGiveAmout, Integer numbers, String memo){
        // 会员卡充值
        TbBizPlaceMemberCard tbBizPlaceMemberCard = (TbBizPlaceMemberCard) MapUtils
                .getObject(map,"tbBizPlaceMemberCard");
        TbBizPlaceMemberCardType tbBizPlaceMemberCardType = (TbBizPlaceMemberCardType) MapUtils
                .getObject(map, "tbBizPlaceMemberCardType");
        TbBizPlaceMemberCard memberCard = new TbBizPlaceMemberCard();
        memberCard.setId(tbBizPlaceMemberCard.getId());
        memberCard.setPlaceId(tbBizPlaceMemberCard.getPlaceId());//add by tim,增加会员卡场馆id
        //充值后有效期
        Date expiryDate = DateUtils.addMonth(tbBizPlaceMemberCard.getDeadLineTime(),
                tbBizPlaceMemberCardType.getAvailableTerm());
        memberCard.setDeadLineTime(expiryDate);

        /*if (!StringUtils.isEmpty(tbBizPlaceMemberCard.getDeadLineTime())){
            DateTime expiryDate = new DateTime(tbBizPlaceMemberCard.getDeadLineTime());
            expiryDate = expiryDate.plusDays(tbBizPlaceMemberCardType.getAvailableTerm() * 31);
            memberCard.setDeadLineTime(expiryDate.toDate());
        }*/

        //本金余额
        BigDecimal amount = BigDecimal.ZERO;
        if (!StringUtils.isEmpty(tbBizPlaceMemberCardType.getInitAmount())){
            tbBizPlaceMemberCard.setSurplusAmount(StringUtils.isEmpty(tbBizPlaceMemberCard.getSurplusAmount())
                    ? BigDecimal.ZERO : tbBizPlaceMemberCard.getSurplusAmount());
            amount = tbBizPlaceMemberCardType.getInitAmount();
            if (!StringUtils.isEmpty(dAmount)){
                amount = new BigDecimal(dAmount);
                amount = amount.setScale(2,BigDecimal.ROUND_HALF_UP);
            }
            BigDecimal surplusAmount = tbBizPlaceMemberCard.getSurplusAmount().add(amount);
            memberCard.setSurplusAmount(surplusAmount);
        }
        // 赠送余额
        if (!StringUtils.isEmpty(tbBizPlaceMemberCardType.getGiveAmount())){
            tbBizPlaceMemberCard.setSurplusGiveAmount(StringUtils.isEmpty(tbBizPlaceMemberCard.getSurplusGiveAmount())
                    ? BigDecimal.ZERO : tbBizPlaceMemberCard.getSurplusGiveAmount());
            BigDecimal giveAmount = tbBizPlaceMemberCardType.getGiveAmount();
            if (!StringUtils.isEmpty(giveAmount) && !StringUtils.isEmpty(dGiveAmout)){
                giveAmount = new BigDecimal(dGiveAmout);
                giveAmount = giveAmount.setScale(2,BigDecimal.ROUND_HALF_UP);
            }
            BigDecimal surplusGiveAmount = tbBizPlaceMemberCard.getSurplusGiveAmount()
                    .add(giveAmount);
            memberCard.setSurplusGiveAmount(surplusGiveAmount);
        }
        // 剩余次数
        if (!StringUtils.isEmpty(tbBizPlaceMemberCardType.getFrequency())){
            Integer frequency = StringUtils.isEmpty(tbBizPlaceMemberCardType.getFrequency()) ? 0 : tbBizPlaceMemberCardType.getFrequency();
            if (!StringUtils.isEmpty(frequency) && null != numbers){
                frequency = numbers;
            }
            Integer oldnumbers = StringUtils
                    .isEmpty(tbBizPlaceMemberCard.getSurplusNumbers()) ? 0 : tbBizPlaceMemberCard.getSurplusNumbers();
            Integer surplusNumbers = oldnumbers + frequency;
            memberCard.setSurplusNumbers(surplusNumbers);
        }

        //插入会员操作记录数据
        TbBizPlaceMemberOpHistory opHistory = new TbBizPlaceMemberOpHistory();
//        opHistory.setMemo(tbBizPlaceMemberCard.getMemo());// 备注
        opHistory.setCreateUid(createUid);
        opHistory.setPlaceId(tbBizPlaceMemberCard.getPlaceId());
        opHistory.setAmount(amount);
        opHistory.setUid(tbBizPlaceMemberCard.getMemberUid());
        opHistory.setInnerCardNo(tbBizPlaceMemberCard.getInnerCardNo());
        opHistory.setCardTypeName(tbBizPlaceMemberCard.getCardName());
        // // TODO: 16/11/11 根据platform设置对应的名称
        opHistory.setOpTypeName("商家端-会员充值");
        opHistory.setOpBeforeAmount(tbBizPlaceMemberCard.getSurplusAmount());
        opHistory.setOpBeforeGiveAmount(tbBizPlaceMemberCard.getSurplusGiveAmount());
        opHistory.setOpAfterAmount(memberCard.getSurplusAmount());
        opHistory.setOpAfterGiveAmount(memberCard.getSurplusGiveAmount());
        opHistory.setSrc(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_RECHARGE);
        opHistory.setSourceType(PlaceConstants.SOURCE_TYPE_SCENEPAY);
        opHistory.setCardTypeId(tbBizPlaceMemberCardType.getId());
        if (PlaceConstants.PLACE_MEMBER_CARD_TYPE_NUMBER == tbBizPlaceMemberCardType.getType()){
            // 次卡的情况
            opHistory.setOpBeforeNumbers(tbBizPlaceMemberCard.getSurplusNumbers());
            opHistory.setOpAfterNumbers(memberCard.getSurplusNumbers());
            opHistory.setOpCardCount(numbers);
            opHistory.setOpBeforeAmount(BigDecimal.ZERO);
            opHistory.setOpAfterAmount(BigDecimal.ZERO);
        }
        TbBizPlaceMember tbBizPlaceMember = (TbBizPlaceMember) MapUtils.getObject(map, "tbBizPlaceMember");
        if (!StringUtils.isEmpty(tbBizPlaceMember)){
            opHistory.setUserName(tbBizPlaceMember.getUserName());
            opHistory.setMobile(tbBizPlaceMember.getMobile());
        }
        opHistory.setMemo(memo);
        opHistory.setState(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_NO);
        opHistory.setType(PlaceConstants.PLACE_MEMBER_HISTORY_TYPE_RECHARGE);
        //获取订单号
        String orderNo = CommonUtils.generateBusinessOrderNo(Constants.PLACE_SYSTEM, tbBizPlaceMember.getUid());
        opHistory.setNo(CommonUtils.generateNo(tbBizPlaceMemberCard.getPlaceId()));
        opHistory.setOrderNo(orderNo);
        opHistory.setAdminPayType(PayTypeEnum.getEnum(adminPayType).getUnifiedId());
        opHistory.setPayType(adminPayType);
        opHistory.setPlatform(PlatformTypeEnum.BACKSTAGE.getId());//后台
        //场馆运营模式
        TbBizPlace tbBizPlace = tbBizPlaceMapper.selectByPrimaryKey(memberCard.getPlaceId());
        opHistory.setBusinessMode(tbBizPlace.getBusinessMode());
        placeMemberService.addPlaceMemberCardOpRecord(opHistory);

        Map<String, Object> result = new HashMap();
        result.put("history", opHistory);
        result.put("membercard", memberCard);
        return APIResponse.returnSuccess(result);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse<?> cardRecharge(Map map, Integer cardID, Integer createUid, Integer adminPayType,  Double dAmount,
                                       Double dGiveAmout, Integer numbers, String memo){
        // 会员卡充值
        TbBizPlaceMemberCard tbBizPlaceMemberCard = (TbBizPlaceMemberCard) MapUtils
                .getObject(map,"tbBizPlaceMemberCard");
        TbBizPlaceMemberCardType tbBizPlaceMemberCardType = (TbBizPlaceMemberCardType) MapUtils
                .getObject(map, "tbBizPlaceMemberCardType");
        TbBizPlaceMemberCard memberCard = new TbBizPlaceMemberCard();
        memberCard.setId(tbBizPlaceMemberCard.getId());
        //充值后有效期
        Date expiryDate = DateUtils.addMonth(tbBizPlaceMemberCard.getDeadLineTime(),
                tbBizPlaceMemberCardType.getAvailableTerm());
        memberCard.setDeadLineTime(expiryDate);

        /*if (!StringUtils.isEmpty(tbBizPlaceMemberCard.getDeadLineTime())){
            DateTime expiryDate = new DateTime(tbBizPlaceMemberCard.getDeadLineTime());
            expiryDate = expiryDate.plusDays(tbBizPlaceMemberCardType.getAvailableTerm() * 31);
            memberCard.setDeadLineTime(expiryDate.toDate());
        }*/

        BigDecimal amount = BigDecimal.ZERO;
        //本金余额
        if (!StringUtils.isEmpty(tbBizPlaceMemberCardType.getInitAmount())){
            tbBizPlaceMemberCard.setSurplusAmount(StringUtils.isEmpty(tbBizPlaceMemberCard.getSurplusAmount())
                    ? BigDecimal.ZERO : tbBizPlaceMemberCard.getSurplusAmount());
            amount = tbBizPlaceMemberCardType.getInitAmount();
            if (!StringUtils.isEmpty(dAmount)){
                amount = new BigDecimal(dAmount);
                amount.setScale(2,BigDecimal.ROUND_HALF_UP);
            }
            BigDecimal surplusAmount = tbBizPlaceMemberCard.getSurplusAmount().add(amount);
            memberCard.setSurplusAmount(surplusAmount);
        }
        // 赠送余额
        if (!StringUtils.isEmpty(tbBizPlaceMemberCardType.getGiveAmount())){
            tbBizPlaceMemberCard.setSurplusGiveAmount(StringUtils.isEmpty(tbBizPlaceMemberCard.getSurplusGiveAmount())
                    ? BigDecimal.ZERO : tbBizPlaceMemberCard.getSurplusGiveAmount());
            BigDecimal giveAmount = tbBizPlaceMemberCardType.getGiveAmount();
            if (!StringUtils.isEmpty(giveAmount) && !StringUtils.isEmpty(dGiveAmout)){
                giveAmount = new BigDecimal(dGiveAmout);
                giveAmount.setScale(2,BigDecimal.ROUND_HALF_UP);
            }
            BigDecimal surplusGiveAmount = tbBizPlaceMemberCard.getSurplusGiveAmount()
                    .add(giveAmount);
            memberCard.setSurplusGiveAmount(surplusGiveAmount);
        }
        // 剩余次数
        if (!StringUtils.isEmpty(tbBizPlaceMemberCardType.getFrequency())){
            Integer frequency = StringUtils
                    .isEmpty(tbBizPlaceMemberCardType.getFrequency()) ? 0 : tbBizPlaceMemberCardType.getFrequency();
            if (!StringUtils.isEmpty(frequency) && numbers != null){
                frequency = numbers;
            }
            Integer oldnumbers = StringUtils
                    .isEmpty(tbBizPlaceMemberCard.getSurplusNumbers()) ? 0 : tbBizPlaceMemberCard.getSurplusNumbers();
            Integer surplusNumbers = oldnumbers + frequency;
            memberCard.setSurplusNumbers(surplusNumbers);
        }

        //插入会员操作记录数据
        TbBizPlaceMemberOpHistory opHistory = new TbBizPlaceMemberOpHistory();
//        opHistory.setMemo(tbBizPlaceMemberCard.getMemo());// 备注
        opHistory.setCreateUid(createUid);
        opHistory.setPlaceId(tbBizPlaceMemberCard.getPlaceId());
        opHistory.setAmount(amount);
        opHistory.setUid(tbBizPlaceMemberCard.getMemberUid());
        opHistory.setInnerCardNo(tbBizPlaceMemberCard.getInnerCardNo());
        opHistory.setCardTypeName(tbBizPlaceMemberCard.getCardName());
        // // TODO: 16/11/11 根据platform设置对应的名称
        opHistory.setOpTypeName("商家端-会员充值");
        opHistory.setOpBeforeAmount(tbBizPlaceMemberCard.getSurplusAmount());
        opHistory.setOpBeforeGiveAmount(tbBizPlaceMemberCard.getSurplusGiveAmount());
        opHistory.setOpAfterAmount(memberCard.getSurplusAmount());
        opHistory.setOpAfterGiveAmount(memberCard.getSurplusGiveAmount());
        opHistory.setSrc(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_RECHARGE);
        opHistory.setSourceType(PlaceConstants.SOURCE_TYPE_SCENEPAY);
        opHistory.setCardTypeId(tbBizPlaceMemberCardType.getId());
        opHistory.setMemo(memo);
        if (PlaceConstants.PLACE_MEMBER_CARD_TYPE_NUMBER == tbBizPlaceMemberCardType.getType()){
            // 次卡的情况
            opHistory.setOpBeforeNumbers(tbBizPlaceMemberCard.getSurplusNumbers());
            opHistory.setOpAfterNumbers(memberCard.getSurplusNumbers());
            opHistory.setOpCardCount(numbers);
            opHistory.setOpBeforeAmount(BigDecimal.ZERO);
            opHistory.setOpAfterAmount(BigDecimal.ZERO);
        }
        TbBizPlaceMember tbBizPlaceMember = (TbBizPlaceMember) MapUtils.getObject(map, "tbBizPlaceMember");
        if (!StringUtils.isEmpty(tbBizPlaceMember)){
            opHistory.setUserName(tbBizPlaceMember.getUserName());
            opHistory.setMobile(tbBizPlaceMember.getMobile());
        }

        opHistory.setState(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_YES);
        opHistory.setType(PlaceConstants.PLACE_MEMBER_HISTORY_TYPE_RECHARGE);
        //获取订单号
        String orderNo = CommonUtils.generateBusinessOrderNo(Constants.PLACE_SYSTEM, tbBizPlaceMember.getUid());
        opHistory.setNo(CommonUtils.generateNo(tbBizPlaceMemberCard.getPlaceId()));
        opHistory.setOrderNo(orderNo);
        opHistory.setAdminPayType(PayTypeEnum.getEnum(adminPayType).getUnifiedId());
        opHistory.setPayType(adminPayType);
        opHistory.setPlatform(PlatformTypeEnum.BACKSTAGE.getId());//后台
        //场馆运营模式
        TbBizPlace tbBizPlace = tbBizPlaceMapper.selectByPrimaryKey(tbBizPlaceMemberCard.getPlaceId());
        opHistory.setBusinessMode(tbBizPlace.getBusinessMode());
        placeMemberService.addPlaceMemberCardOpRecord(opHistory);

        ReqOrderHistory reqOrderHistory = placeMemberService.tbBizPlaceMemberOpHistory2ReqOrderHistory(opHistory);
        if (null != reqOrderHistory){
            try {
                placeOrderUtilService.insertOrderHistory(reqOrderHistory);
            } catch (Exception e) {
                logger.error("会员开卡充值历史记录插入失败");
//                    throw new BizException("会员开卡充值历史记录插入失败");
            }
        }

        // 更新会员卡表数据
        this.placeMemberService.updatePlaceMemberCard(memberCard);

        //发送充值短信
        //根据系统参数获取客服密码
//        TbCommonParameter parameterVo= baseService.getParameterByKey(SysParameterConfigEnum.CONFIG_APP_SERVICE_MOBILE.getCode());
        //新增开卡发送短信
       /* String [] args=new String[4];
        args[0]=tbBizPlaceMember.getUserName()!=null?tbBizPlaceMember.getUserName():"";
        args[1]= DateUtils.getCurrentTime();
        args[2]= tbBizPlaceMemberCardType.getName();
        args[3]=parameterVo!=null?parameterVo.getParameterValue():"";
        placeTicketService.asyncSendSms(tbBizPlaceMember.getMobile(), SmsApi.MESSAGE_TEMPLATE_PLACE_READD_MEMBER_INFO, args, true);*/
        PlacePrintVo placePrintVo = new PlacePrintVo();
        placePrintVo.setPlaceOrderId(opHistory.getOrderNo());
        placePrintVo.setBusinessType(PlaceConstants.ORDER_USE_RECHARGE_CARD);
        placePrintVo.setIsMember(PlaceConstants.NO);
        return APIResponse.returnSuccess(placeOrderUtilService.getPrintOrderInfo(placePrintVo));
    }

    @Override
    public APIResponse<?> getVipPayDetail(Integer placeId, Integer cardTypeId) {
        APIResponse<?> response = placeMemberService.getVipPayDetail(placeId, cardTypeId);
        if (!response.isRet()){
            return response;
        }
        List<RespPayInfo> payInfos = new ArrayList<>();
        RespPayInfo respPayInfo1 = new RespPayInfo();
        respPayInfo1.setPayId(PlaceConstants.PAY_WAY_ALIPAY);
        respPayInfo1.setPayType("支付宝");
        payInfos.add(respPayInfo1);
        RespPayInfo respPayInfo2 = new RespPayInfo();
        respPayInfo2.setPayId(PlaceConstants.PAY_WAY_WEICHAT);
        respPayInfo2.setPayType("微信支付");
        payInfos.add(respPayInfo2);
        Map map = new HashMap();
        map.put("payInfo", payInfos);
        map.put("cardType",response.getData());
        return APIResponse.returnSuccess(map);
    }

    @Override
    public APIResponse<List<RespPlaceMemberCardDetail>> getMyVenueVipList(Integer userId) {
       /* APIResponse<?> cardResponse = placeMemberService.getTbBizPlaceMemberCardsByUid(userId);
        if (!cardResponse.isRet()){
            return APIResponse.returnFail(cardResponse.getErrmsg());
        }*/
        Map<Integer, List<TbBizPlaceMemberCard>> map = new HashMap<>();
        List<TbBizPlaceMemberCard> tbBizPlaceMemberCards = placeMemberService.getTbBizPlaceMemberCardsByUid(userId);
       /* if (CollectionUtils.isEmpty(tbBizPlaceMemberCards)){
            return APIResponse.returnFail("没有会员卡信息");
        }*/
        for (TbBizPlaceMemberCard tbBizPlaceMemberCard : tbBizPlaceMemberCards){
            if (!map.containsKey(tbBizPlaceMemberCard.getPlaceId())){
                List<TbBizPlaceMemberCard> tbBizPlaceMemberCardList = new ArrayList<>();
                tbBizPlaceMemberCardList.add(tbBizPlaceMemberCard);
                map.put(tbBizPlaceMemberCard.getPlaceId(), tbBizPlaceMemberCardList);
                continue;
            }
            List<TbBizPlaceMemberCard> tempTbBizPlaceMemberCards = map.get(tbBizPlaceMemberCard.getPlaceId());
            tempTbBizPlaceMemberCards.add(tbBizPlaceMemberCard);
            map.put(tbBizPlaceMemberCard.getPlaceId(),tempTbBizPlaceMemberCards);
        }
      /*  if (MapUtils.isEmpty(map)){
            return APIResponse.returnFail("用户没有会员卡");
        }*/
        return placeMemberService.getRespPlaceMemberCardDetail(map);

    }

    @Override
    public APIResponse<?> buyVenueVip(Integer userId, Integer cardTypeId, Integer payTypeId, Integer platformType,Integer refereesId, Integer larkAppId) {
        TbBizPlaceMemberCardType tbBizPlaceMemberCardType = this.placeMemberService.getMemberTypeById(cardTypeId);
        if (StringUtils.isEmpty(tbBizPlaceMemberCardType)){
            return APIResponse.returnFail("会员卡类型不存在");
        }
        if (!ObjectUtils.isEmpty(tbBizPlaceMemberCardType.getStatus())
                && PlaceConstants.PLACE_MEMBER_CARD_TYPE_STATUS_NO == tbBizPlaceMemberCardType.getStatus()){
            return APIResponse.returnFail("会员卡类型已经停用");
        }
        //app请求不支持俱乐部会员卡（议价会员卡）充值
        if(!ObjectUtils.isEmpty(tbBizPlaceMemberCardType.getSourceType())
                && PlaceConstants.PLACE_MEMBER_CARD_TYPE_BARGAINING_MEMBER == tbBizPlaceMemberCardType.getSourceType()){
            return APIResponse.returnFail("议价会员卡不支持app端充值");
        }

        TbBizPlaceMemberCard tbBizPlaceMemberCard = placeMemberService.getTbBizPlaceMemberCardByTypeId(userId, cardTypeId);
        //如果果老会员屏蔽C端购买充值功
        if (!StringUtils.isEmpty(tbBizPlaceMemberCard) && tbBizPlaceMemberCard.getStatus().intValue()
                != PlaceConstants.PLACE_MEMBER_CARD_STATUS_CANCEL
            && tbBizPlaceMemberCard.getIsOldMember().intValue() == 1){
            return APIResponse.returnFail("此卡不支持充值,请联系场馆工作人员");
        }
        if (!StringUtils.isEmpty(tbBizPlaceMemberCard)
                && tbBizPlaceMemberCard.getDeadLineTime() != null
                && tbBizPlaceMemberCard.getDeadLineTime().getTime() < new Date().getTime()){
            tbBizPlaceMemberCard.setStatus(PlaceConstants.PLACE_MEMBER_CARD_STATUS_CANCEL);
            placeMemberService.updatePlaceMemberCard(tbBizPlaceMemberCard);
            return placeMemberService.buyVenueVip(userId, tbBizPlaceMemberCardType, payTypeId, platformType,refereesId,larkAppId);
        }

        if(placeMemberService.isExistsMemberCard(tbBizPlaceMemberCardType.getPlaceId(),
                tbBizPlaceMemberCardType.getId(), userId)){
            // 会员卡充值
            TbBizPlaceMemberCard card = placeMemberService.getTbBizPlaceMemberCardByTypeId(userId, cardTypeId);
            if (StringUtils.isEmpty(card)){
                return APIResponse.returnFail("没有对应类型的会员卡");
            }
            return placeMemberService.vipCardReChargeDetail(userId, cardTypeId, payTypeId, card, platformType,refereesId);
        }

        return placeMemberService.buyVenueVip(userId, tbBizPlaceMemberCardType, payTypeId, platformType,refereesId,larkAppId);
    }

    @Override
    public APIResponse<?> cardRecharge(Integer cardID, Integer createUid, Integer adminPayType,  Double dAmount,
                                       Double dGiveAmout, Integer numbers,String scanCode, String memo) {
        // 校验会员卡有效性
        APIResponse<?> response = this.placeMemberService.vaildCardByID(cardID,null);
        if (!response.isRet()) {
            return response;
        }
        Map map = (Map) response.getData();

        boolean isScanPayFlag = false;
        if(MerchantClientPayType.getMatchScanPayType().containsKey(adminPayType.toString())){
            isScanPayFlag = true;
        }

        boolean isCompanyFlag = false;//对公转账
        if (PlaceConstants.PLACE_ADMIN_PAY_WAYS_COMPANY.equals(adminPayType.toString())){//对公转账支付方式匹配
            isCompanyFlag = true;
        }

        if (isScanPayFlag) {
            APIResponse mapResponse = null;
            try {
                mapResponse = this.cardRechargeForScanPay(map, cardID, createUid, adminPayType, dAmount, dGiveAmout,
                        numbers, memo);
            }catch (Exception e){
                e.printStackTrace();
                return APIResponse.returnFail("扫码记录生成失败");
            }
            if (mapResponse.isRet() && mapResponse.getData() != null) {
                Map<String, Object> resultMap = (Map<String, Object>) mapResponse.getData();
                TbBizPlaceMemberOpHistory opHistory = (TbBizPlaceMemberOpHistory) resultMap.get("history");
                TbBizPlaceMemberCard tbBizPlaceMemberCard = (TbBizPlaceMemberCard) resultMap.get("membercard");
                PlaceScanOrderPayVo placeScanOrderPayVo = new PlaceScanOrderPayVo();
                placeScanOrderPayVo.setReceivedAmount(opHistory.getAmount());
                placeScanOrderPayVo.setAdminPayType(adminPayType.toString());
                placeScanOrderPayVo.setScanCode(scanCode);
                placeScanOrderPayVo.setTbBizPlaceOrder(null);
                placeScanOrderPayVo.setTbBizPlacePrivateOrder(null);
                placeScanOrderPayVo.setReqTicketPay(null);
                placeScanOrderPayVo.setTbBizPlaceMemberCard(tbBizPlaceMemberCard);
                placeScanOrderPayVo.setTbBizPlaceMemberOpHistory(opHistory);
                try {
                    return placeOrderService.scanOrderPay(placeScanOrderPayVo);
                }catch (Exception e){
                    return APIResponse.returnFail(e.getMessage());
                }
            } else {
                return APIResponse.returnFail("扫码会员充值失败");
            }
        } else if (isCompanyFlag){
            APIResponse mapResponse = null;
            try {
                mapResponse = this.cardRechargeForScanPay(map, cardID, createUid, adminPayType, dAmount, dGiveAmout,
                        numbers, memo);
            }catch (Exception e){
                e.printStackTrace();
                return APIResponse.returnFail("扫码记录生成失败");
            }
            if (mapResponse.isRet() && mapResponse.getData() != null) {
                Map<String, Object> resultMap = (Map<String, Object>) mapResponse.getData();
                TbBizPlaceMemberOpHistory opHistory = (TbBizPlaceMemberOpHistory) resultMap.get("history");
                TbBizPlaceMemberCard tbBizPlaceMemberCard = (TbBizPlaceMemberCard) resultMap.get("membercard");

                //插入审核记录
                PlaceFinanceAuditVo placeFinanceAuditVo = placeOrderUtilService.tbBizPlaceMemberOpHistory2PlaceFinanceAuditVo(opHistory);
                if (!StringUtils.isEmpty(placeFinanceAuditVo)){
                    financeService.createAuditRecord(placeFinanceAuditVo);
                }

                PlacePrintVo placePrintVo = new PlacePrintVo();
                placePrintVo.setPlaceOrderId(opHistory.getOrderNo());
                placePrintVo.setBusinessType(PlaceConstants.ORDER_USE_RECHARGE_CARD);
                placePrintVo.setIsMember(PlaceConstants.NO);
                return APIResponse.returnSuccess(placeOrderUtilService.getPrintOrderInfo(placePrintVo));
            } else {
                return APIResponse.returnFail("对公转账会员充值失败");
            }
        } else{
            try {
                return this.cardRecharge(map, cardID, createUid, adminPayType, dAmount, dGiveAmout, numbers, memo);
            }catch (Exception e){
                return APIResponse.returnFail("充值失败");
            }
        }

    }

    @Override
    public APIResponse<?> vipCardPayRecordList(Integer userId, Integer pageNum, Integer pageSize) {
        PageObj<List<TbBizPlaceMemberOpHistory>> tbBizPlaceMemberOpHistoryList =
                placeMemberService.getMemberOpHistory(userId, null,
                pageNum, pageSize);
        if (StringUtils.isEmpty(tbBizPlaceMemberOpHistoryList)){
            return APIResponse.returnFail("没有交易记录");
        }
        return APIResponse.returnSuccess(tbBizPlaceMemberOpHistoryList);
    }

    @Override
    public APIResponse<?> vipCardReChargeDetail(Integer userId, Integer cardTypeId, Integer payTypeId, Integer platformType,Integer refereesId) {
        TbBizPlaceMemberCard card = placeMemberService.getTbBizPlaceMemberCardByTypeId(userId, cardTypeId);
        if (StringUtils.isEmpty(card)){
            return APIResponse.returnFail("没有对应类型的会员卡");
        }
        return placeMemberService.vipCardReChargeDetail(userId, cardTypeId, payTypeId, card, platformType,refereesId);
    }

    @Override
    public APIResponse<?> vipCardNoPayRecordList(String vipNo, Integer userId, Integer pageNum, Integer pageSize) {
        TbBizPlaceMemberCard tbBizPlaceMemberCard = placeMemberService.getPlaceMemberCardInfo(vipNo, null, userId);
        if (StringUtils.isEmpty(tbBizPlaceMemberCard)){
            return APIResponse.returnFail("没有此会员卡号");
        }
        PageObj<List<TbBizPlaceMemberOpHistory>> tbBizPlaceMemberOpHistoryList =
                placeMemberService.getMemberOpHistory(userId, tbBizPlaceMemberCard,
                        pageNum, pageSize);
        if (StringUtils.isEmpty(tbBizPlaceMemberOpHistoryList)){
            return APIResponse.returnFail("没有交易记录");
        }
        List<TbBizPlaceMemberOpHistory> list = tbBizPlaceMemberOpHistoryList.getItems();
        List<RespCardPayList> respCardPayList = this.placeMemberService.getRespCardPayList(list);
        if (CollectionUtils.isNotEmpty(respCardPayList)){
            PageObj<List<RespCardPayList>> pageObj = new PageObj<>();
            pageObj.setItems(respCardPayList);
            pageObj.setSize(pageSize);
            pageObj.setPageNum(pageNum);
            pageObj.setTotal(respCardPayList.size());
            return APIResponse.returnSuccess(pageObj);
        }
        return APIResponse.returnSuccess();
    }

    @Override
    public APIResponse<?> orderCancelOperate(ReqOrderOperate reqOrderOperate) {
        return placeMemberService.orderCancelOperate(reqOrderOperate);
    }

    @Override
    public APIResponse<?> orderCompletePayOperate(ReqOrderOperate reqOrderOperate,  TbBizPlaceOrder tbBizPlaceOrder) {
        return placeMemberService.orderCompletePayOperate(reqOrderOperate, tbBizPlaceOrder);
    }

    @Override
    public APIResponse orderUnsubscribeOperate(ReqOrderOperate reqOrderOperate, TbBizPlaceOrder tbBizPlaceOrder) {
        return placeMemberService.orderUnsubscribeOperate(reqOrderOperate, tbBizPlaceOrder);
    }

    @Override
    public APIResponse<?> orderCompleteUnsubscribeOperate(ReqOrderOperate reqOrderOperate, TbBizPlaceOrder tbBizPlaceOrder) {
        return placeMemberService.orderCompleteUnsubscribeOperate(reqOrderOperate, tbBizPlaceOrder);
    }

    @Override
    public APIResponse<?> orderCancleToUnsubscribeOperate(ReqOrderOperate reqOrderOperate, TbBizPlaceOrder tbBizPlaceOrder) {
        return placeMemberService.orderCancleToUnsubscribeOperate(reqOrderOperate, tbBizPlaceOrder);
    }


    /**
     * 添加会员及会员卡
     * @param reqMemberCard
     * @return
     */
    @Override
    @Transactional
    public APIResponse addMemberInfo(ReqMemberCard reqMemberCard,boolean isScanPay) {
        if (null != reqMemberCard){
            Map scanPayMap = new HashMap();
            if (null != reqMemberCard.getCardTypeId()){
                TbBizPlaceMemberCardType cardType = placeMemberService.getMemberTypeById(reqMemberCard.getCardTypeId());

                TbBizPlaceMember member = placeMemberService.getPlaceMember(reqMemberCard.getPhone());
                Integer uid = null;
                if (null != member){
                    uid = member.getUid();
                    //已存在，则更新身份证
                    member.setIdCard(reqMemberCard.getIdCardNo());
                    placeMemberService.updatePlaceMember(member); // 更新会员信息
                } else {
                    // 注册到用户中心，返回uid
                    uid = registerToUserCenter(reqMemberCard, cardType);
                    // 保存会员信息
                    /*if (isScanPay){
                        //扫码支付  会员状态——>冻结
                        savePlaceMember(reqMemberCard, uid,PlaceConstants.PLACE_MEMBER_STATUS_FROZEN);
                    }else{*/
                    if (uid == null){
                        return APIResponse.returnFail("注册新用户失败");
                    }
                    savePlaceMember(reqMemberCard, uid,PlaceConstants.PLACE_MEMBER_STATUS_NORMAL);
                    /*}*/
                }

                if (null != cardType){
                    // 会员卡
                    if (placeMemberService.isExistsMemberCard(reqMemberCard.getPlaceId(),cardType.getId(), uid)){
                        return APIResponse.returnFail("会员卡已存在");
                    }
                    TbBizPlaceMemberCard memberCard = new TbBizPlaceMemberCard();
                    memberCard.setMemberUid(uid); // 用户uid
                    memberCard.setCardType(cardType.getType());
                    memberCard.setPlaceId(reqMemberCard.getPlaceId());
                    Map map = new HashMap();
                    map.put("placeId",reqMemberCard.getPlaceId());
                    String memberCardNum = cardNoService.getCardNo(map);
                    memberCard.setInnerCardNo(memberCardNum); // 会员卡
                    memberCard.setCardTypeId(cardType.getId());
                    memberCard.setSourceType(cardType.getSourceType());
                    memberCard.setCardName(cardType.getName());
                    memberCard.setDisplayName(reqMemberCard.getMemberName());
                    memberCard.setStatus(PlaceConstants.PLACE_MEMBER_CARD_STATUS_NORMAL);
                    memberCard.setGiveAmountIsUse(cardType.getGiveAmountIsUse());
                    Calendar calendar = Calendar.getInstance();
                    memberCard.setIsOldMember(reqMemberCard.getIsOldMember());

                    int month = 0;
                    if (cardType.getAvailableTerm() >= PlaceConstants.MAX_CARD_TYPE_MONTH){
                        // 无期限卡
                        month = PlaceConstants.MAX_CARD_TYPE_MONTH;
                    } else {
                        month = cardType.getAvailableTerm();
                    }
                    if (Constants.BYTE_ONE == reqMemberCard.getIsClubMember()){
                        // 俱乐部会员（议价会员） 俱乐部会员充值金额，赠送余额，折扣都可以调整
                        memberCard.setAmount(reqMemberCard.getAmount()==null?BigDecimal.ZERO:reqMemberCard.getAmount()); // 初始充值金额
                        memberCard.setSurplusAmount(reqMemberCard.getAmount()==null?BigDecimal.ZERO:reqMemberCard.getAmount()); // 余额
                        memberCard.setGiveAmount(reqMemberCard.getGiveAmount()==null?BigDecimal.ZERO:reqMemberCard.getGiveAmount());   // 赠送金额
                        memberCard.setSurplusGiveAmount(reqMemberCard.getGiveAmount()==null?BigDecimal.ZERO:reqMemberCard.getGiveAmount()); // 赠送余额
                        memberCard.setDiscount(reqMemberCard.getDiscount()==null?100:reqMemberCard.getDiscount());
                    } else {
                        // 普通会员充值金额，赠送余额，折扣来自会员卡类型
                        memberCard.setAmount(cardType.getInitAmount()); // 初始充值金额
                        memberCard.setSurplusAmount(cardType.getInitAmount()); // 余额
                        if (PlaceConstants.PLACE_MEMBER_CARD_TYPE_NUMBER.equals(cardType.getType())){
                            //次卡余额置0
                            memberCard.setSurplusAmount(BigDecimal.ZERO);
                        }
                        memberCard.setGiveAmount(cardType.getGiveAmount()==null ? BigDecimal.ZERO :cardType.getGiveAmount());   // 赠送金额
                        memberCard.setSurplusGiveAmount(cardType.getGiveAmount()==null ? BigDecimal.ZERO :cardType.getGiveAmount()); // 赠送余额
                        memberCard.setDiscount(cardType.getDiscount());
                    }


                    TbBizPlaceMemberOpHistory opHistory = new TbBizPlaceMemberOpHistory();
                    // 与场馆老板结算的老会员做特殊处理  1充值金额不依赖于会员卡类型初始金额  2 付款方式默认为与场馆老板结算
                    Integer payWayBoss = Integer.valueOf(PlaceConstants.PLACE_ADMIN_PAY_WAYS_BOSS);
                    if (null != reqMemberCard.getIsOldMember() && Constants.BYTE_ONE == reqMemberCard.getIsOldMember()){
                        memberCard.setAmount(reqMemberCard.getAmount()); // 初始充值金额
                        memberCard.setSurplusAmount(reqMemberCard.getAmount()); // 余额
                        memberCard.setGiveAmount(BigDecimal.ZERO);   // 赠送金额
                        memberCard.setSurplusGiveAmount(BigDecimal.ZERO); // 赠送余额
                        opHistory.setAdminPayType(PayTypeEnum.getEnum(payWayBoss).getUnifiedId()); // 付款方式
                        opHistory.setPayType(payWayBoss);
                    } else {
                        opHistory.setAdminPayType(PayTypeEnum.getEnum(reqMemberCard.getAdminPayType()).getUnifiedId());
                        opHistory.setPayType(reqMemberCard.getAdminPayType());
                    }
                    calendar.add(Calendar.MONTH, month);
                    memberCard.setDeadLineTime(calendar.getTime()); // 会员卡截止日
                    memberCard.setNumbers(cardType.getFrequency()!=null ? cardType.getFrequency() : 0);
                    memberCard.setSurplusNumbers(cardType.getFrequency()!=null ? cardType.getFrequency() : 0);
                    if (isScanPay){
                        //扫码支付  卡状态——>注销  , 已删除
                        memberCard.setStatus(PlaceConstants.PLACE_MEMBER_CARD_STATUS_CANCEL);
                        memberCard.setIsDelete(Constants.IS_DELETE_TRUE);
                    }else{
                        memberCard.setStatus(Constants.BYTE_ONE); // 启用
                        memberCard.setIsDelete(Constants.IS_DELETE_FALSE);
                    }
                    memberCard.setCategoryIds(cardType.getCategoryIds());
                    memberCard.setAvailableStartTime(cardType.getAvailableStartTime());
                    memberCard.setAvailableEndTime(cardType.getAvailableEndTime());
                    memberCard.setCreateUid(reqMemberCard.getUid());
                    memberCard.setRefereesId(reqMemberCard.getUid());
                    memberCard.setMemo(reqMemberCard.getMemo());
                    //memberCard.setCreatTime(Calendar.getInstance().getTime());
                    //memberCard.setUpdateTime(Calendar.getInstance().getTime());
                    memberCard.setCreateTime(Calendar.getInstance().getTime());
                    memberCard.setUpdateTime(Calendar.getInstance().getTime());
                    //是否支持门票
                    if(null != cardType.getIsSupportTickets()){
                        memberCard.setIsSupportTickets( cardType.getIsSupportTickets());
                    }else{
                        memberCard.setIsSupportTickets((byte)0);
                    }
                    if (memberCard.getDiscount() == null){
                        memberCard.setDiscount(new Double(100));
                    }else if (memberCard.getDiscount().equals(new Double(0))){
                        memberCard.setDiscount(new Double(100));
                    }
                    placeMemberService.addPlaceMemberCard(memberCard);
                    
                    
                    if(!isScanPay){ //非扫码发短信
                    	   //根据系统参数获取客服密码
                        TbBizPlace place=placeBaseService.getPlaceById(reqMemberCard.getPlaceId());
                        List<String> mobileList=new ArrayList<>();
                        List<String> paramList=new ArrayList<>();

                        //新增开卡发送短信
                        String [] args=new String[4];
                        args[0]=DateUtils.getCurrentTime();
                        args[1]=place!=null?place.getName():"";
                        args[2]= cardType.getName();
                        // 联系电话优先取订场咨询电话，订场电话为空时，取客服电话
                        TbBizPlaceAttach placeAttach = placeBaseService.getBizPlaceAttach(reqMemberCard.getPlaceId());
                        if (null != placeAttach && org.apache.commons.lang3.StringUtils.isNotEmpty(placeAttach.getBookingConsultPhone())){
                            args[3]=placeAttach.getBookingConsultPhone();
                        } else {
                            // 获取系统配置的百灵鸟客服热线
                            TbCommonParameter parameterVo = baseService.getParameterByKey(SysParameterConfigEnum.CONFIG_APP_SERVICE_MOBILE.getCode());
                            args[3]=parameterVo!=null?parameterVo.getParameterValue():"";
                        }
                        mobileList.add(reqMemberCard.getPhone());
                        paramList.addAll(Arrays.asList(args));
                        try{
                            //placeTicketService.asyncSendSms(reqMemberCard.getPhone(), SmsApi.MESSAGE_TEMPLATE_PLACE_ADD_MEMBER_INFO,args,true);
                            placeSmsService.sendSms(mobileList,SmsApi.MESSAGE_TEMPLATE_PLACE_ADD_MEMBER_INFO, PlaceConstants.PLACE_SMS_TYPE_MESSAGE,paramList);
                        }catch(Exception e){
                            logger.info("短信发送失败-------->"+e.getMessage());
                        }
                    }
                    
                 

                    // 增加会员交易明细
                    opHistory.setMemo(memberCard.getMemo());// 备注
                    opHistory.setCreateUid(reqMemberCard.getUid());
                    opHistory.setPlaceId(memberCard.getPlaceId());
                    opHistory.setAmount(memberCard.getAmount());
                    opHistory.setUid(memberCard.getMemberUid());
                    opHistory.setInnerCardNo(memberCard.getInnerCardNo());
                    opHistory.setCardTypeName(memberCard.getCardName());
                    opHistory.setOpTypeName("商家端-开通会员");
                    opHistory.setOpBeforeAmount(BigDecimal.ZERO);
                    opHistory.setOpBeforeGiveAmount(BigDecimal.ZERO);
                    opHistory.setOpAfterAmount(memberCard.getSurplusAmount());
                    opHistory.setOpAfterGiveAmount(memberCard.getSurplusGiveAmount());
                    opHistory.setSrc(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_OPEN);
                    opHistory.setSourceType(PlaceConstants.SOURCE_TYPE_SCENEPAY);
                    opHistory.setCardTypeId(memberCard.getCardTypeId());
                    if (PlaceConstants.PLACE_MEMBER_CARD_TYPE_NUMBER == cardType.getType()){
                        // 次卡的情况
                        opHistory.setOpBeforeNumbers(0);
                        opHistory.setOpAfterNumbers(cardType.getFrequency());
                    }
                    TbBizPlaceMember tbBizPlaceMember = placeMemberService.getPlaceMemberByUid(memberCard.getMemberUid());
                    if (!StringUtils.isEmpty(tbBizPlaceMember)){
                        opHistory.setUserName(tbBizPlaceMember.getUserName());
                        opHistory.setMobile(tbBizPlaceMember.getMobile());
                    }

                    if (isScanPay){
                        //扫码支付  明细无效
                        opHistory.setState(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_NO);
                    }else{
                        opHistory.setState(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_YES);
                    }
                    opHistory.setType(PlaceConstants.PLACE_MEMBER_HISTORY_TYPE_RECHARGE);
                    //获取订单号
                    String orderNo = CommonUtils.generateBusinessOrderNo(Constants.PLACE_SYSTEM, reqMemberCard.getUid());
                    opHistory.setNo(CommonUtils.generateNo(memberCard.getPlaceId()));
                    opHistory.setOrderNo(orderNo);

                    opHistory.setPlatform(PlatformTypeEnum.BACKSTAGE.getId());//后台
                    //场馆运营模式
                    TbBizPlace tbBizPlace = tbBizPlaceMapper.selectByPrimaryKey(memberCard.getPlaceId());
                    opHistory.setBusinessMode(tbBizPlace.getBusinessMode());
                    placeMemberService.addPlaceMemberCardOpRecord(opHistory);

                    scanPayMap.put("memberCard",memberCard);
                    scanPayMap.put("opHistory",opHistory);

                    //增加会员开卡流水
                    ReqOrderHistory reqOrderHistory = placeMemberService.tbBizPlaceMemberOpHistory2ReqOrderHistory(opHistory);
                    if (null != reqOrderHistory){
                        try {
                            placeOrderUtilService.insertOrderHistory(reqOrderHistory);
                        } catch (Exception e) {
                            logger.error("会员开卡充值历史记录插入失败");
//                    throw new BizException("会员开卡充值历史记录插入失败");
                        }
                    }
                }
            }
            return APIResponse.returnSuccess(scanPayMap);
        } else {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
        }
    }

    /**
     * 保存会员信息
     * @param reqMemberCard
     * @param uid
     */
    public void savePlaceMember(ReqMemberCard reqMemberCard, Integer uid,byte status) {
        TbBizPlaceMember member = new TbBizPlaceMember();
        member.setMobile(reqMemberCard.getPhone()); // 手机
        member.setUserName(reqMemberCard.getMemberName());
        //member.setStatus(PlaceConstants.PLACE_MEMBER_STATUS_NORMAL);
        member.setStatus(status);
        member.setType((byte)1); // 场馆会员
        member.setIdCard(reqMemberCard.getIdCardNo()); // 身份证号
        member.setGender(reqMemberCard.getGender()); // 性别
        member.setUid(uid); // 用户ID
        //member.setMemo(reqMemberCard.getMemo());
        placeMemberService.addPlaceMember(member); // 添加场馆会员
    }

    /**
     * 注册到用户中心
     * @param reqMemberCard
     * @param cardType
     * @return
     */
    private Integer registerToUserCenter(ReqMemberCard reqMemberCard, TbBizPlaceMemberCardType cardType) {
        ReqBackstageUser reqBackstageUser = new ReqBackstageUser();
        reqBackstageUser.setMobile(reqMemberCard.getPhone());
        reqBackstageUser.setAdminUid(reqMemberCard.getUid()); // 当前后台操作用户
        reqBackstageUser.setMemberCardName(cardType.getName());
        reqBackstageUser.setMemberName(reqMemberCard.getMemberName());
        APIResponse retUser = userServiceFacade.registerMemberUser(reqBackstageUser);
        Integer uid = null;
        if (null != retUser && null != retUser.getData()){
            uid = (Integer)retUser.getData(); // 当前注册会员的uid
        }
        return uid;
    }

    /**
     * 更新会员卡信息
     * @param reqMemberCard
     * @return
     */
    @Override
    public APIResponse updateMemberCard(ReqMemberCard reqMemberCard) {
        Date opAfterDeadTime=null;
        if (reqMemberCard.getOpMonth()==null){
            reqMemberCard.setOpMonth(0);
        }
        if (reqMemberCard.getOpMonth().intValue()!=0){
            if (reqMemberCard.getOpMonth().intValue()>0) {
                opAfterDeadTime=DateUtils.addTime(reqMemberCard.getOpBeforeDeadTime(),reqMemberCard.getOpMonth(),0);
            }else{
                opAfterDeadTime=DateUtils.getTimesSubtract(reqMemberCard.getOpBeforeDeadTime(),0,Math.abs(reqMemberCard.getOpMonth()));
            }
            logger.info(">>>>>>>>"+DateUtils.transferDateToString(opAfterDeadTime));
        }
        if (null != reqMemberCard){
            if (null != reqMemberCard.getMemberCardId()){
                TbBizPlaceMemberCard dbMemberCard= placeMemberService.getTbBizPlaceMemberCardById(reqMemberCard.getMemberCardId());
                if (reqMemberCard.getCardTypeId() != null &&
                        !reqMemberCard.getCardTypeId().equals(dbMemberCard.getCardTypeId()) &&
                        dbMemberCard.getAmount().compareTo(dbMemberCard.getSurplusAmount()) != 0){
                    return APIResponse.returnFail("会员卡已使用，不能变更卡类型");
                }

                TbBizPlaceMemberCardType cardType = placeMemberService.getMemberTypeById(reqMemberCard.getCardTypeId());
                dbMemberCard.setCardTypeId(reqMemberCard.getCardTypeId());
                //dbMemberCard.setAmount(cardType.getInitAmount());
                //dbMemberCard.setSurplusAmount(cardType.getInitAmount());

                if (opAfterDeadTime!=null){
                    dbMemberCard.setDeadLineTime(opAfterDeadTime);
                }
                dbMemberCard.setMemo(reqMemberCard.getMemo());
                dbMemberCard.setDisplayName(reqMemberCard.getMemberName());
                dbMemberCard.setIsOldMember(reqMemberCard.getIsOldMember());
                placeMemberService.updatePlaceMemberCard(dbMemberCard); // 更新会员卡信息

                //只更新身份证
                TbBizPlaceMember member = placeMemberService.getPlaceMemberByUid(dbMemberCard.getMemberUid());
                //member.setUserName(reqMemberCard.getMemberName());
                member.setIdCard(reqMemberCard.getIdCardNo());
                placeMemberService.updatePlaceMember(member); // 更新会员信息
            }
            //会员卡有效期修改操作记录
            if (reqMemberCard.getOpMonth().intValue()!=0){
                //增加有效期
            if (reqMemberCard.getOpMonth().intValue()>0) {
                if (opAfterDeadTime != null) {
                    List<TbBizPlaceMemberOpHistory> list = placeMemberService.getMinDeadLineTimeByInnerCard(reqMemberCard.getInnerCardNo());
                    if (list != null && list.size() > 0) {
                        if (list.get(0).getOpBeforeDeadTime() != null) {
                            String from = DateUtils.transferDateToString(list.get(0).getOpBeforeDeadTime());
                            String to = DateUtils.transferDateToString(opAfterDeadTime);
                            try {
                                int month = DateUtils.dateDiffMonth(from, to);
                                if (month > 24) {
                                    return APIResponse.returnFail("该卡有效期已累计增加达到24个月，无法增加");
                                }
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    if (!DateUtils.dateCompare(opAfterDeadTime, new Date(), true)) {
                        return APIResponse.returnFail("有效期不能小于当前时间");
                    }
                }
            }
                //减少有效期
                if (reqMemberCard.getOpMonth().intValue()<0) {
                    if (opAfterDeadTime != null) {
                        if (!DateUtils.dateCompare(opAfterDeadTime, new Date(), true)) {
                            return APIResponse.returnFail("有效期不能小于当前时间");
                        }
                    }
                }
                //会员卡操作记录
                String orderNo = CommonUtils.generateBusinessOrderNo(Constants.PLACE_SYSTEM,reqMemberCard.getUid());
                TbBizPlaceMemberOpHistory tbBizPlaceMemberOpHistory = new TbBizPlaceMemberOpHistory();
                tbBizPlaceMemberOpHistory.setCreateUid(reqMemberCard.getUid());
                tbBizPlaceMemberOpHistory.setPlaceId(reqMemberCard.getPlaceId());
                tbBizPlaceMemberOpHistory.setUpdateTime(new Date());
                //tbBizPlaceMemberOpHistory.setAmount(price);
                //tbBizPlaceMemberOpHistory.setPayType(PlaceConstants.PAY_WAY_SCENEPAY);
                //tbBizPlaceMemberOpHistory.setAdminPayType(reqPlaceGoodsVo.getPayType());
                tbBizPlaceMemberOpHistory.setPlatform(PlatformTypeEnum.BACKSTAGE.getId());
                tbBizPlaceMemberOpHistory.setCreateTime(new Date());
                tbBizPlaceMemberOpHistory.setInnerCardNo(reqMemberCard.getInnerCardNo());
                //TODO 生成流水号
                tbBizPlaceMemberOpHistory.setNo(CommonUtils.generateNo(reqMemberCard.getPlaceId()));
                tbBizPlaceMemberOpHistory.setOrderNo(orderNo);
                tbBizPlaceMemberOpHistory.setOpTypeName("调整有效期");
                if (!StringUtils.isEmpty(reqMemberCard.getPhone())) {
                    Integer uid = placeMemberService.getUidByNameAndPhone(null, reqMemberCard.getPhone());
                    tbBizPlaceMemberOpHistory.setUid(uid);
                }
                tbBizPlaceMemberOpHistory.setUserName(reqMemberCard.getMemberName());
                tbBizPlaceMemberOpHistory.setMobile(reqMemberCard.getPhone());
                TbBizPlaceMemberCard tbBizPlaceMemberCard1 = placeMemberService.getCardInfoByMemberCardId(reqMemberCard.getMemberCardId());
                tbBizPlaceMemberOpHistory.setCardTypeName(tbBizPlaceMemberCard1.getCardName());
                tbBizPlaceMemberOpHistory.setMemo(reqMemberCard.getMemo());
                tbBizPlaceMemberOpHistory.setState(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_YES);
                tbBizPlaceMemberOpHistory.setSrc(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_OPDEADTIME);
                tbBizPlaceMemberOpHistory.setCardTypeId(tbBizPlaceMemberCard1.getCardTypeId());
                tbBizPlaceMemberOpHistory.setOpBeforeDeadTime(reqMemberCard.getOpBeforeDeadTime());
                tbBizPlaceMemberOpHistory.setOpMonth(Math.abs(reqMemberCard.getOpMonth()));
                tbBizPlaceMemberOpHistory.setOpAfterDeadTime(opAfterDeadTime);
                tbBizPlaceMemberOpHistory.setSourceType(PlaceConstants.SOURCE_TYPE_SCENEPAY);
                if(tbBizPlaceMemberCard1.getCardType()==4){
                    tbBizPlaceMemberOpHistory.setOpAfterNumbers(tbBizPlaceMemberCard1.getSurplusNumbers());
                    tbBizPlaceMemberOpHistory.setOpBeforeNumbers(tbBizPlaceMemberCard1.getSurplusNumbers());
                }else {
                    tbBizPlaceMemberOpHistory.setOpAfterAmount(tbBizPlaceMemberCard1.getSurplusAmount());
                    tbBizPlaceMemberOpHistory.setOpAfterGiveAmount(tbBizPlaceMemberCard1.getSurplusGiveAmount());
                }
                placeMemberService.savePlaceMemberOpHistory(tbBizPlaceMemberOpHistory);
            }
        }
        return APIResponse.returnSuccess();
    }

    /**
     * 获取会员卡列表
     * @param reqMemberSearch
     * @return
     */
    @Override
    public PageObj<List<RespMemberCardInfo>> getPlaceMemberCardList(ReqPlaceMemberSearch reqMemberSearch) {

        Integer pageNum = 0;
        Integer pageSize = Constants.DEFAULT_PAGE_SIZE;
        String keywords = null;
        Integer placeId = null;
        Integer cardType = null;
        Byte status = null;
        Byte orderType = null;
        Integer cityId = null;
        String placeCode = null;
        String placeName = null;
        if (reqMemberSearch != null) {
            pageNum = reqMemberSearch.getPageNum();
            pageSize = reqMemberSearch.getPageSize();
            keywords = reqMemberSearch.getKey();
            placeId = reqMemberSearch.getPlaceId();
            cardType = reqMemberSearch.getCardType();
            status = reqMemberSearch.getStatus();
            cityId = reqMemberSearch.getCityId();
            placeCode = reqMemberSearch.getPlaceCode();
            placeName = reqMemberSearch.getPlaceName();
            orderType = reqMemberSearch.getOrderType();
        }

        // 共享会员的场馆做特殊处理
        boolean isShareVip =false;
        if (null != placeId){
            TbBizPlaceAttach placeAttach = placeBaseService.getBizPlaceAttach(placeId);
            if (null != placeAttach &&
                    null != placeAttach.getIsVipShare() &&
                    Constants.YES == placeAttach.getIsVipShare()){
                // 场馆共享会员卡时
                String vipShareNo = placeAttach.getVipShareNo();
                List<TbBizPlaceAttach> placeAttachList = placeBaseService.getSharePlaceVipByShareNo(vipShareNo);
                if (null == placeAttachList || placeAttachList.size() <= 1){
                    isShareVip = false;
                }
                String placeIdStr = packagePlaceIdStr(placeAttachList);
                if (org.apache.commons.lang3.StringUtils.isNotEmpty(placeIdStr)){
                    reqMemberSearch.setPlaceIdStr(placeIdStr);
                    isShareVip = true;
                }
            }
        }
        //List<RespMemberCardInfo> placeMemberCardList = new ArrayList<RespMemberCardInfo>();
        List<RespMemberCardInfo> memberCardList = new ArrayList<RespMemberCardInfo>();
        int totalNum = 0;
        if (isShareVip){
            totalNum = placeMemberService.countPlaceMemberCard(reqMemberSearch);
            int begin = pageNum * pageSize;
            reqMemberSearch.setBeginIndex(begin);
            reqMemberSearch.setPageSize(pageSize);
            memberCardList = placeMemberService.selectMemberCardList(reqMemberSearch);
        } else {
            totalNum = placeMemberService.countPlaceMemberCard(keywords, placeId, cardType, status, cityId, placeCode, placeName, orderType);
            memberCardList = placeMemberService.selectMemberCardList(pageNum * pageSize, pageSize,
                    placeId, keywords, cardType, status, cityId, placeCode, placeName, orderType);
        }

        //List<RespMemberCardInfo> memberCardList = placeMemberService.selectMemberCardList(pageNum * pageSize, pageSize, reqMemberSearch);
        if (CollectionUtils.isNotEmpty(memberCardList)){
            for (RespMemberCardInfo respMemberCardInfo : memberCardList){
                if (respMemberCardInfo.getCardStatus()
                        != PlaceConstants.PLACE_MEMBER_CARD_STATUS_NORMAL.intValue()){
                    respMemberCardInfo.setMemberCardTypeStatus(PlaceConstants.PLACE_MEMBER_CARD_STATUS_CANCEL.intValue());
                    continue;
                }
                if ((!StringUtils.isEmpty(respMemberCardInfo.getDeadLine())
                        && respMemberCardInfo.getDeadLine().getTime() < new Date().getTime())){
                    respMemberCardInfo.setMemberCardTypeStatus(PlaceConstants.PLACE_MEMBER_CARD_STATUS_CANCEL.intValue());
                    continue;
                }
                respMemberCardInfo.setMemberCardTypeStatus(PlaceConstants.PLACE_MEMBER_CARD_STATUS_NORMAL.intValue());
            }
        }
        PageObj<List<RespMemberCardInfo>> result = PageObj.create(totalNum, pageNum, pageSize, memberCardList);
        return result;
    }

    private String packagePlaceIdStr(List<TbBizPlaceAttach> placeAttachList) {
        StringBuffer strBuffPlaceIds = new StringBuffer();
        if (null == placeAttachList || placeAttachList.size() == 0){
            return "";
        }
        strBuffPlaceIds.append("(");
        for (TbBizPlaceAttach attach : placeAttachList){
            strBuffPlaceIds.append(attach.getPlaceId());
            strBuffPlaceIds.append(",");
        }
        int index = strBuffPlaceIds.toString().lastIndexOf(',');
        if(index != -1){
            strBuffPlaceIds.deleteCharAt(index);
        }
        strBuffPlaceIds.append(")");
        return strBuffPlaceIds.toString();

    }

    /**
     *  注销会员卡
     * @param memberCardId
     * @return
     */
    public APIResponse logOffMemberCard(Integer memberCardId,Integer adminUid) {
        TbBizPlaceMemberCard memberCard = placeMemberService.getTbBizPlaceMemberCardById(memberCardId);
        APIResponse result = placeMemberService.logOffMemberCard(memberCard); // 注销会员卡
        if (null != result && result.isRet()){
           // 添加日志
            businessLogService.insertIntoBusinessLog(memberCardId,PlaceConstants.LOG_TYPE_PLACE_MEMBER,adminUid,"注销会员卡","注销会员卡");
            placeMemberService.addLogOffMemberCardByHistory(memberCard, memberCard.getMemberUid(),
                    adminUid, PlatformTypeEnum.BACKSTAGE.getId());
        } else {
            return APIResponse.returnFail("注销会员卡失败");
        }
        return APIResponse.returnSuccess();
    }

    /**
     * 挂失会员卡
     * @param memberCardId
     * @return
     */
    public APIResponse reportLossMemberCard(Integer memberCardId,Integer adminUid) {
        TbBizPlaceMemberCard memberCard = placeMemberService.getTbBizPlaceMemberCardById(memberCardId);
        APIResponse result = placeMemberService.reportLossMemberCard(memberCard); // 挂失会员卡
        if (null != result && result.isRet()){
            // 添加日志
            businessLogService.insertIntoBusinessLog(memberCardId,PlaceConstants.LOG_TYPE_PLACE_MEMBER,adminUid,"挂失会员卡","挂失会员卡");
        } else {
            return APIResponse.returnFail("挂失会员卡失败");
        }
        return APIResponse.returnSuccess();
    }

    /**
     * 获取指定场馆会员卡类型
     * @param placeId
     * @return
     */
    @Override
    public APIResponse getMemberTypeByPlaceId(Integer placeId) {
        return APIResponse.returnSuccess(placeMemberService.getMemberTypeByPlaceId(placeId));
    }

    /**
     * 调整余额
     * @param reqAdjustMemberBalance
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse adjustMemberCardBalance(ReqAdjustMemberBalance reqAdjustMemberBalance) {
        TbBizPlaceMemberCard memberCard = placeMemberService.getTbBizPlaceMemberCardById(reqAdjustMemberBalance.getMemberCardId());
        if (null != memberCard){
            if (!PlaceConstants.PLACE_MEMBER_CARD_STATUS_NORMAL.equals(memberCard.getStatus())){
                return APIResponse.returnFail("会员卡状态异常,不能调整余额!");
            }

            BigDecimal opAfterAmount = new BigDecimal(0);
            BigDecimal opBeforeAmount = new BigDecimal(0);
            opBeforeAmount=memberCard.getSurplusAmount();
            TbBizPlaceMemberOpHistory opHistory = new TbBizPlaceMemberOpHistory();
            opHistory.setCreateUid(reqAdjustMemberBalance.getUid());
            opHistory.setPlaceId(memberCard.getPlaceId());
            opHistory.setAmount(reqAdjustMemberBalance.getAdjustAmount());
            opHistory.setUid(memberCard.getMemberUid());
            opHistory.setInnerCardNo(memberCard.getInnerCardNo());
            opHistory.setCardTypeName(memberCard.getCardName());
            opHistory.setOpTypeName("会员卡余额调整");
            opHistory.setOpBeforeAmount(memberCard.getSurplusAmount());
            opHistory.setOpBeforeGiveAmount(memberCard.getSurplusGiveAmount());
            opHistory.setOpAfterGiveAmount(memberCard.getSurplusGiveAmount());
            opHistory.setSrc(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_ADJUST);
            opHistory.setOpBeforeNumbers(0);
            opHistory.setOpAfterNumbers(0);
            TbBizPlaceMember tbBizPlaceMember = placeMemberService.getPlaceMemberByUid(memberCard.getMemberUid());
            if (!StringUtils.isEmpty(tbBizPlaceMember)){
                opHistory.setUserName(tbBizPlaceMember.getUserName());
                opHistory.setMobile(tbBizPlaceMember.getMobile());
            }
            if (Constants.BYTE_ONE == reqAdjustMemberBalance.getOperateType()){
                // 增加余额
                opAfterAmount = memberCard.getSurplusAmount().add(reqAdjustMemberBalance.getAdjustAmount());
            } else {
                // 扣减余额
                if (reqAdjustMemberBalance.getAdjustAmount().compareTo(memberCard.getSurplusAmount()) > 0){
                    return APIResponse.returnFail("调整金额不能大于会员卡余额!");
                }
                opAfterAmount = memberCard.getSurplusAmount().subtract(reqAdjustMemberBalance.getAdjustAmount());
            }
            memberCard.setSurplusAmount(opAfterAmount);
            placeMemberService.updatePlaceMemberCard(memberCard);


            /* //根据系统参数获取客服密码
            TbBizPlace place=placeBaseService.getPlaceById(memberCard.getPlaceId());
            //修改余额后发送短信给会员
            String [] args=new String[6];
            args[0]=place!=null?place.getName():"";
            args[1]=memberCard!=null?memberCard.getCardName():"";
            args[2]= DateUtils.getCurrentTime();
            args[3]=opBeforeAmount.toString();
            args[4]=memberCard!=null?memberCard.getSurplusAmount().toString():"";
            // 联系电话优先取订场咨询电话，订场电话为空时，取客服电话
            TbBizPlaceAttach placeAttach = placeBaseService.getBizPlaceAttach(memberCard.getPlaceId());
            if (null != placeAttach && org.apache.commons.lang3.StringUtils.isNotEmpty(placeAttach.getBookingConsultPhone())){
                args[5]=placeAttach.getBookingConsultPhone();
            } else {
                // 获取系统配置的百灵鸟客服热线
                TbCommonParameter parameterVo = baseService.getParameterByKey(SysParameterConfigEnum.CONFIG_APP_SERVICE_MOBILE.getCode());
                args[5]=parameterVo!=null?parameterVo.getParameterValue():"";
            }

            try{
                placeTicketService.asyncSendSms(tbBizPlaceMember.getMobile(), SmsApi.MESSAGE_TEMPLATE_PLACE_BALANCE_NOTICE,args,true);
            }catch (Exception e){
                logger.info("短信发送失败！>>>>>>"+e.getMessage());
            }*/
            opHistory.setState(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_YES);
            opHistory.setOpAfterAmount(opAfterAmount);  // 调整后金额
            opHistory.setType(reqAdjustMemberBalance.getOperateType());
            opHistory.setMemo(reqAdjustMemberBalance.getReason());
            //获取订单号
            String orderNo = CommonUtils.generateBusinessOrderNo(Constants.PLACE_SYSTEM, reqAdjustMemberBalance.getUid());
            opHistory.setNo(CommonUtils.generateNo(memberCard.getPlaceId()));
            opHistory.setOrderNo(orderNo);
            opHistory.setPayType(null);
            opHistory.setPlatform(5);//后台
            opHistory.setSourceType(PlaceConstants.SOURCE_TYPE_SCENEPAY);
            placeMemberService.addPlaceMemberCardOpRecord(opHistory);
        }
        return APIResponse.returnSuccess();
    }

    /**
     * 会员导入
     * @param reqMemberCards
     * @return
     */
    @Override
    public APIResponse importPlaceMembers(ReqMemberCards reqMemberCards) {
        if (null != reqMemberCards){
            Integer placeId = reqMemberCards.getPlaceId();
            Integer adminUid = reqMemberCards.getUid();
            List<TbBizPlaceMemberCardType> memberCardList = placeMemberService.getMemberTypeByPlaceId(placeId);
            Set<Integer> cardTypeSet = new HashSet<Integer>();
            for (TbBizPlaceMemberCardType cardType : memberCardList){
                cardTypeSet.add(cardType.getId());
            }
            //场馆运营模式
            TbBizPlace tbBizPlace = tbBizPlaceMapper.selectByPrimaryKey(placeId);
            int count = 0; // 导入条数
            String batchNo = CommonUtils.generateOrderNo(placeId);
            if (null != reqMemberCards.getMemberCardList()){
               for (ReqMemberCard reqMemberCard : reqMemberCards.getMemberCardList()){
                    if (!cardTypeSet.contains(reqMemberCard.getCardTypeId())){
                        continue;
                    }
                   reqMemberCard.setUid(adminUid);
                   reqMemberCard.setPlaceId(placeId);
                   reqMemberCard.setBatchNo(batchNo);
                   // 新用户导入需要注册到用户中心 一条条保存
                   if (importPlaceMember(reqMemberCard,tbBizPlace)){
                       count++;
                   }
               }
            }
            if (count > 0 && reqMemberCards.getIsOldMember() == 0){
                // 场馆买断会员导入 需要财务审批
                PlaceFinanceAuditVo placeFinanceAuditVo = new PlaceFinanceAuditVo();
                placeFinanceAuditVo.setPlaceId(placeId);
                placeFinanceAuditVo.setBusinessType(PlaceFinanceAuditVo.FINANCE_AUDIT_IMPORT_MEMBER); // 审核类型：场馆新会员导入
                placeFinanceAuditVo.setSubType(PlaceFinanceAuditVo.FINANCE_AUDIT_SUBTYPE_EIGHT); // 审核子类型：会员导入
                placeFinanceAuditVo.setBusinessNo(placeId.toString());
                placeFinanceAuditVo.setSubjectUid(adminUid);
                TbAdminUser tbAdminUser = AdminUserService.getAdminUser(adminUid);
                if (!org.springframework.util.StringUtils.isEmpty(tbAdminUser)){
                    placeFinanceAuditVo.setSubjectUserName(tbAdminUser.getTrueName());
                }
                financeService.createAuditRecord(placeFinanceAuditVo);
            }
        }
        return APIResponse.returnSuccess();
    }

    /**
     * 会员卡导入
     * @param reqMemberCard
     */
    private boolean importPlaceMember(ReqMemberCard reqMemberCard,TbBizPlace tbBizPlace) {
        if (null == reqMemberCard){
            return false;
        }
        if (null == reqMemberCard.getCardTypeId()) {
            return false;
        }
        TbBizPlaceMemberCardType cardType = placeMemberService.getMemberTypeById(reqMemberCard.getCardTypeId());

        TbBizPlaceMember member = placeMemberService.getPlaceMember(reqMemberCard.getPhone());
        Integer uid = null;
        if (null != member){
            uid = member.getUid();
        } else {
            // 注册到用户中心，返回uid
            uid = registerToUserCenter(reqMemberCard, cardType);
            // 保存会员信息
            savePlaceMember(reqMemberCard, uid,PlaceConstants.PLACE_MEMBER_STATUS_NORMAL);
        }
        if (null == cardType){
            return false;
        }
        // 会员卡
        if (placeMemberService.isExistsMemberCard(reqMemberCard.getPlaceId(),cardType.getId(), uid)){
            logger.warn("会员卡已经存在" + reqMemberCard.getPhone());
            return false;
        }
        TbBizPlaceMemberCard memberCard = new TbBizPlaceMemberCard();
        memberCard.setMemberUid(uid); // 用户uid
        memberCard.setCardType(cardType.getType());
        memberCard.setPlaceId(reqMemberCard.getPlaceId());
        Map map = new HashMap();
        map.put("placeId",reqMemberCard.getPlaceId());
        String memberCardNum = cardNoService.getCardNo(map);
        memberCard.setInnerCardNo(memberCardNum); // 会员卡
        memberCard.setCardTypeId(cardType.getId());
        memberCard.setSourceType(cardType.getSourceType());
        memberCard.setCardName(cardType.getName());
        if (reqMemberCard.getIsOldMember() == 0){
            // 导入的新会员需要审核
            memberCard.setStatus(PlaceConstants.PLACE_MEMBER_CARD_STATUS_TO_AUDIT);
        } else {
            memberCard.setStatus(PlaceConstants.PLACE_MEMBER_CARD_STATUS_NORMAL);
        }
        memberCard.setGiveAmountIsUse(cardType.getGiveAmountIsUse());
        Calendar calendar = Calendar.getInstance();


        memberCard.setAmount(cardType.getInitAmount()); // 初始充值金额
        memberCard.setSurplusAmount(reqMemberCard.getAmount() == null ? BigDecimal.ZERO : reqMemberCard.getAmount()); // 余额
        memberCard.setGiveAmount(cardType.getGiveAmount() == null ? BigDecimal.ZERO : cardType.getGiveAmount());   // 赠送金额
        memberCard.setSurplusGiveAmount(reqMemberCard.getGiveAmount() == null ? BigDecimal.ZERO : reqMemberCard.getGiveAmount()); // 赠送余额
        memberCard.setDiscount(reqMemberCard.getDiscount());
        memberCard.setIsOldMember(reqMemberCard.getIsOldMember());

        if (PlaceConstants.PLACE_MEMBER_CARD_TYPE_NUMBER.equals(cardType.getType())){
            //次卡余额 置为0
            memberCard.setSurplusAmount(BigDecimal.ZERO);
        }
        memberCard.setDiscount(cardType.getDiscount());
        int month = 0;
        if (null != reqMemberCard.getDeadLine()){
            // 导入时Excel有截止日期
            memberCard.setDeadLineTime(DateTimeUtils.convertString2Date("yyyy-MM-dd", reqMemberCard.getDeadLine()));
        } else {
            if (null == cardType.getAvailableTerm()){
                month = 12;
            } else {
                month = cardType.getAvailableTerm();
            }
            calendar.add(Calendar.MONTH, month);
            memberCard.setDeadLineTime(calendar.getTime()); // 会员卡截止日
        }
        // 导入时次卡优先取用户录入的
        if (null != reqMemberCard.getSurplusNumbers()){
            memberCard.setSurplusNumbers(reqMemberCard.getSurplusNumbers()); // 剩余次数
        } else {
            memberCard.setSurplusNumbers(cardType.getFrequency()!=null ? cardType.getFrequency() : 0);
        }
        memberCard.setNumbers(cardType.getFrequency());
        //memberCard.setStatus(Constants.BYTE_ONE); // 启用
        memberCard.setIsDelete(Constants.IS_DELETE_FALSE);
        memberCard.setCategoryIds(cardType.getCategoryIds());
        memberCard.setAvailableStartTime(cardType.getAvailableStartTime());
        memberCard.setAvailableEndTime(cardType.getAvailableEndTime());
        memberCard.setCreateUid(reqMemberCard.getUid());
        memberCard.setMemo(reqMemberCard.getMemo());
        memberCard.setCreateTime(Calendar.getInstance().getTime());
        memberCard.setUpdateTime(Calendar.getInstance().getTime());
        placeMemberService.addPlaceMemberCard(memberCard);

        // 增加会员交易明细
        TbBizPlaceMemberOpHistory opHistory = new TbBizPlaceMemberOpHistory();
        opHistory.setMemo(memberCard.getMemo());// 备注
        opHistory.setCreateUid(reqMemberCard.getUid());
        opHistory.setPlaceId(memberCard.getPlaceId());
        // 因为充值时还可以调整余额，取余额字段作为操作金额
        opHistory.setAmount(memberCard.getSurplusAmount());
        opHistory.setUid(memberCard.getMemberUid());
        opHistory.setInnerCardNo(memberCard.getInnerCardNo());
        opHistory.setCardTypeName(memberCard.getCardName());
        opHistory.setOpTypeName("商家端-开通会员");
        opHistory.setOpBeforeAmount(BigDecimal.ZERO);
        opHistory.setOpBeforeGiveAmount(BigDecimal.ZERO);
        opHistory.setOpAfterAmount(memberCard.getSurplusAmount());
        opHistory.setOpAfterGiveAmount(memberCard.getSurplusGiveAmount());
        opHistory.setSrc(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_SRC_OPEN);
        opHistory.setSourceType(PlaceConstants.SOURCE_TYPE_SCENEPAY);
        if (PlaceConstants.PLACE_MEMBER_CARD_TYPE_NUMBER == cardType.getType()){
            // 次卡的情况
            opHistory.setOpBeforeNumbers(0);
            opHistory.setOpAfterNumbers(cardType.getFrequency());
        }
        TbBizPlaceMember tbBizPlaceMember = placeMemberService.getPlaceMemberByUid(memberCard.getMemberUid());
        if (!StringUtils.isEmpty(tbBizPlaceMember)){
            opHistory.setUserName(tbBizPlaceMember.getUserName());
            opHistory.setMobile(tbBizPlaceMember.getMobile());
        }
        if (reqMemberCard.getIsOldMember() == 0){
            // 导入的新会员需要审核
            opHistory.setState(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_NO);
        } else {
            opHistory.setState(PlaceConstants.PLACE_MEMBER_CARD_OP_HISTORY_YES);
        }
        opHistory.setType(PlaceConstants.PLACE_MEMBER_HISTORY_TYPE_RECHARGE);
        //获取订单号
        String orderNo = CommonUtils.generateBusinessOrderNo(Constants.PLACE_SYSTEM, reqMemberCard.getUid());
        opHistory.setNo(CommonUtils.generateNo(memberCard.getPlaceId()));
        opHistory.setOrderNo(orderNo);
        // 会员卡导入时付款方式为场馆老板结算
        Integer payWayBoss = Integer.valueOf(PlaceConstants.PLACE_ADMIN_PAY_WAYS_BOSS);
        opHistory.setAdminPayType(PayTypeEnum.getEnum(payWayBoss).getUnifiedId());
        opHistory.setPayType(payWayBoss);
        opHistory.setPlatform(5);//后台

        opHistory.setBusinessMode(tbBizPlace.getBusinessMode());
        placeMemberService.addPlaceMemberCardOpRecord(opHistory);
        return true;
    }

    /**
     * 根据会员卡Id取得指定会员卡
     * @param memberCardId
     * @return
     */
    @Override
    public APIResponse getMemberCardId(Integer memberCardId) {
        RespMemberCardInfo result = new RespMemberCardInfo();

        TbBizPlaceMemberCard dbMemberCard= placeMemberService.getTbBizPlaceMemberCardById(memberCardId);
        TbBizPlaceMember member = placeMemberService.getPlaceMemberByUid(dbMemberCard.getMemberUid());
        result.setMemberCardId(memberCardId);
        result.setPlaceId(dbMemberCard.getPlaceId());
        result.setMemberCardType(dbMemberCard.getCardTypeId());
        result.setMemberCardTypeName(dbMemberCard.getCardName());
        result.setMemberCardNum(dbMemberCard.getInnerCardNo());
        result.setMemberName(dbMemberCard.getDisplayName());
        result.setMemberId(member.getId());
        result.setIdCardNo(member.getIdCard());
        result.setMobile(member.getMobile());
        result.setMemo(dbMemberCard.getMemo()); // 备注
        result.setDeadLine(dbMemberCard.getDeadLineTime());
        result.setMemberUid(dbMemberCard.getMemberUid());
        result.setStatus((int)dbMemberCard.getStatus());
        result.setIsOldMember(dbMemberCard.getIsOldMember());
        return APIResponse.returnSuccess(result);
    }

    /**
     * 批量导入，不发送短信(只用于初始化数据）
     * @param reqMemberCards
     * @return
     */
    @Override
    public APIResponse importPlaceMembersBatch(ReqMemberCards reqMemberCards) {

        if (null != reqMemberCards){
            List<ReqBackstageUser> requestMemberList = new ArrayList<ReqBackstageUser>();

            Integer placeId = reqMemberCards.getPlaceId();
            //Integer uid = reqMemberCards.getUid();
            Map<String, ReqMemberCard> requestMemberMap= new HashMap<String, ReqMemberCard>();
            for (ReqMemberCard reqMemberCard : reqMemberCards.getMemberCardList()){
                if (StringUtils.isEmpty(reqMemberCard.getPhone())){
                    continue;
                }
                ReqBackstageUser reqBackstageUser = new ReqBackstageUser();
                reqBackstageUser.setMobile(reqMemberCard.getPhone());
                reqBackstageUser.setMemberName(reqMemberCard.getMemberName());
                requestMemberList.add(reqBackstageUser);
                requestMemberMap.put(reqMemberCard.getPhone(),reqMemberCard);
            }

            // 注册为用户，返回 mobile uid map
            APIResponse response = userServiceFacade.batchRegisterMemberUser(requestMemberList);
            Map<String,Integer> mobileUidMap = (Map<String,Integer>)response.getData();
            Iterator iterator = mobileUidMap.entrySet().iterator();
            while(iterator.hasNext()) {
                Map.Entry entry = (Map.Entry) iterator.next();
                String mobile = (String) entry.getKey();
                Integer userId = (Integer) entry.getValue();
                // 注册为会员
                TbBizPlaceMember member = new TbBizPlaceMember();
                member.setMobile(mobile); // 手机
                if (requestMemberMap.containsKey(mobile)) {
                    member.setUserName(requestMemberMap.get(mobile).getMemberName());
                    member.setIdCard(requestMemberMap.get(mobile).getIdCardNo()); // 身份证号
                    member.setGender(requestMemberMap.get(mobile).getGender()); // 性别
                }
                member.setStatus(PlaceConstants.PLACE_MEMBER_STATUS_NORMAL);
                member.setType((byte) 1); // 场馆会员
                member.setUid(userId); // 用户ID
                //member.setMemo(reqMemberCard.getMemo());
                try {
                    placeMemberService.addPlaceMember(member); // 添加场馆会员
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (null != requestMemberMap.get(mobile).getCardTypeId()) {
                    TbBizPlaceMemberCardType cardType = placeMemberService.getMemberTypeById(requestMemberMap.get(mobile).getCardTypeId());
                    // 会员卡
                    if (placeMemberService.isExistsMemberCard(reqMemberCards.getPlaceId(), cardType.getId(), userId)) {
                        continue;
                    }
                    TbBizPlaceMemberCard memberCard = new TbBizPlaceMemberCard();
                    memberCard.setMemberUid(userId); // 用户uid
                    memberCard.setCardType(cardType.getType());
                    memberCard.setPlaceId(reqMemberCards.getPlaceId());
                    Map map = new HashMap();
                    map.put("placeId", reqMemberCards.getPlaceId());
                    String memberCardNum = cardNoService.getCardNo(map);
                    memberCard.setInnerCardNo(memberCardNum); // 会员卡
                    memberCard.setCardTypeId(cardType.getId());
                    memberCard.setCardName(cardType.getName());
                    memberCard.setStatus(PlaceConstants.PLACE_MEMBER_CARD_STATUS_NORMAL);
                    Calendar calendar = Calendar.getInstance();

                    int month = 0;
                    if (cardType.getAvailableTerm() >= PlaceConstants.MAX_CARD_TYPE_MONTH) {
                        // 无期限卡
                        month = PlaceConstants.MAX_CARD_TYPE_MONTH;
                    } else {
                        month = cardType.getAvailableTerm();
                    }
                    calendar.add(Calendar.MONTH, month);
                    memberCard.setDeadLineTime(calendar.getTime()); // 会员卡截止日期
                    memberCard.setAmount(cardType.getInitAmount()); // 初始充值金额
                    memberCard.setSurplusAmount(cardType.getInitAmount()); // 余额
                    memberCard.setGiveAmount(cardType.getGiveAmount() == null ? BigDecimal.ZERO : cardType.getGiveAmount());   // 赠送金额
                    memberCard.setSurplusGiveAmount(cardType.getGiveAmount() == null ? BigDecimal.ZERO : cardType.getGiveAmount()); // 赠送余额
                    memberCard.setDiscount(cardType.getDiscount());
                    memberCard.setNumbers(cardType.getFrequency());
                    memberCard.setSurplusNumbers(cardType.getFrequency() != null ? cardType.getFrequency() : 0);
                    memberCard.setStatus(Constants.BYTE_ONE); // 启用
                    memberCard.setIsDelete(Constants.IS_DELETE_FALSE);
                    memberCard.setCategoryIds(cardType.getCategoryIds());
                    memberCard.setAvailableStartTime(cardType.getAvailableStartTime());
                    memberCard.setAvailableEndTime(cardType.getAvailableEndTime());
                    memberCard.setCreateUid(reqMemberCards.getUid());
                    //memberCard.setCreatTime(Calendar.getInstance().getTime());
                    //memberCard.setUpdateTime(Calendar.getInstance().getTime());
                    memberCard.setCreateTime(Calendar.getInstance().getTime());
                    memberCard.setUpdateTime(Calendar.getInstance().getTime());
                    placeMemberService.addPlaceMemberCard(memberCard);
                }
            }
        }
        return APIResponse.returnSuccess();
    }

    /**
     * 封装app场馆会员卡类型列表
     * @param placeId
     * @return
     */
    @Override
    public APIResponse getPlaceMemberCardTypeList(Integer placeId) {
        List<TbBizPlaceMemberCardType> cardTypeList = placeMemberService.getMemberCardTypeListByPlaceId(placeId,true);
        List<RespMemberCardType> result = new ArrayList<RespMemberCardType>();
        for (TbBizPlaceMemberCardType cardType : cardTypeList){
            RespMemberCardType retCardType = new RespMemberCardType();
            assembleRespMemberCard(placeId, cardType, retCardType);
            result.add(retCardType);
        }
        return APIResponse.returnSuccess(result);
    }

    /**
     * 组装客户端需要的场馆会员卡信息
     * @param placeId
     * @param cardType
     * @param retCardType
     */
    private void assembleRespMemberCard(Integer placeId, TbBizPlaceMemberCardType cardType, RespMemberCardType retCardType) {
        retCardType.setId(cardType.getId());  // 卡类型Id
        retCardType.setName(cardType.getName()); // 可类型名称
        retCardType.setDescription(cardType.getDescription());
        retCardType.setType(cardType.getType());              // 类型
        retCardType.setInitAmount(cardType.getInitAmount());  // 初始金额
        retCardType.setGiveAmount(cardType.getGiveAmount()); // 赠送金额
        retCardType.setDiscount(cardType.getDiscount());  // 折扣
        retCardType.setFrequency(cardType.getFrequency()); // 次数
        retCardType.setAvailableStartTime(DateTimeUtils.convertDate2String("HH:mm", cardType.getAvailableStartTime()));
        retCardType.setAvailableEndTime(DateTimeUtils.convertDate2String("HH:mm", cardType.getAvailableEndTime()));
        retCardType.setAvailableTerm(cardType.getAvailableTerm());
        retCardType.setPlaceId(placeId);
        retCardType.setCardTypeId(cardType.getId());
        retCardType.setSourceType(cardType.getSourceType());
        retCardType.setStatus(cardType.getStatus());

        if (!StringUtils.isEmpty(cardType.getCategoryIds())){
            retCardType.setCategoryIds(JSON.parseObject(cardType.getCategoryIds(),List.class));
        }
        StringBuffer strBufferCategorys = new StringBuffer();
        // StringBuffer strBufferAvailableTime = new StringBuffer();
        Set<Integer> categoryIdSet = new HashSet(retCardType.getCategoryIds());
        Iterator<Integer> it = categoryIdSet.iterator();
        while(it.hasNext()){
            // 运动项目名称拼接
            Integer catergoryId = it.next();
            if (null != catergoryId) {
                if (null != PlaceCategoryEnum.getEnum(catergoryId)) {
                    strBufferCategorys.append(PlaceCategoryEnum.getEnum(catergoryId).getLabel());
                    strBufferCategorys.append("、");
                }
            }
        }
        int index = strBufferCategorys.toString().lastIndexOf('、');
        if(index != -1){
            strBufferCategorys.deleteCharAt(index);
        }
        retCardType.setCategoryNameStr(strBufferCategorys.toString());
        // 增加客户端显示联系电话
        setPhone(placeId, retCardType);
    }

    private void setPhone(Integer placeId, RespMemberCardType retCardType) {
        // 联系电话优先取订场咨询电话，订场电话为空时，取客服电话
        TbBizPlaceAttach placeAttach = placeBaseService.getBizPlaceAttach(placeId);
        if (null != placeAttach && org.apache.commons.lang3.StringUtils.isNotEmpty(placeAttach.getBookingConsultPhone())){
            retCardType.setTelephone(placeAttach.getBookingConsultPhone());
        } else {
            // 获取系统配置的百灵鸟客服热线
            TbCommonParameter parameterVo = baseService.getParameterByKey(SysParameterConfigEnum.CONFIG_APP_SERVICE_MOBILE.getCode());
            if (null != parameterVo){
                retCardType.setTelephone(parameterVo.getParameterValue());
            }
        }
    }

    /**
     * 获取会员卡详情
     * @param innerCardNo
     * @return
     */
    public APIResponse getPlaceMemberCardDetail(String innerCardNo){
        RespPlaceMemberCardDetail cardDetail = new RespPlaceMemberCardDetail();
        TbBizPlaceMemberCard tbBizPlaceMemberCard = placeMemberService.getPlaceMemberCardInfo(innerCardNo,null,null);
        if (null != tbBizPlaceMemberCard){
            // 余额
            if (null == tbBizPlaceMemberCard.getSurplusGiveAmount()){
                // 赠送余额为空
                cardDetail.setBalance(tbBizPlaceMemberCard.getSurplusAmount());
            } else {
                cardDetail.setBalance(tbBizPlaceMemberCard.getSurplusAmount().add(tbBizPlaceMemberCard.getSurplusGiveAmount()));
            }
            if (null != tbBizPlaceMemberCard.getCreateTime()){
                cardDetail.setValidStart(DateTimeUtils.convertDate2String("yyyy.MM.dd", tbBizPlaceMemberCard.getCreateTime()));
            }
            if (null != tbBizPlaceMemberCard){
                cardDetail.setValidEnd(DateTimeUtils.convertDate2String("yyyy.MM.dd", tbBizPlaceMemberCard.getDeadLineTime()));
            }
            cardDetail.setNumbers(tbBizPlaceMemberCard.getSurplusNumbers()); // 剩余次数

            TbBizPlaceMember member = placeMemberService.getPlaceMemberByUid(tbBizPlaceMemberCard.getMemberUid());
            if (null != member){
                cardDetail.setUserName(member.getUserName());
            }
            TbBizPlaceMemberCardType cardType = placeMemberService.getMemberTypeById(tbBizPlaceMemberCard.getCardTypeId());
            RespMemberCardType retCardType = new RespMemberCardType();

            assembleRespMemberCard(tbBizPlaceMemberCard.getPlaceId(), cardType, retCardType);
            cardDetail.setVipDetail(retCardType);
            //设置是否老会员
            cardDetail.setIsOldMember(tbBizPlaceMemberCard.getIsOldMember());

            //获取场馆栏目
            Integer placeId = tbBizPlaceMemberCard.getPlaceId();
            if (!StringUtils.isEmpty(placeId)){
                List<TbBizPlaceCategory> list = placeBaseService.getPlaceCategoryList(placeId);
                if (CollectionUtils.isNotEmpty(list)){
                    TbBizPlaceCategory category = list.get(0);
                    cardDetail.setCategoryId(category.getCategoryId());
                }
            }
        }
        return APIResponse.returnSuccess(cardDetail);
    }

    /**
     * 冻结会员
     * @param memberId
     * @param adminUid
     * @return
     */
    @Override
    @Transactional
    public APIResponse frozenMember(Integer memberId, Integer adminUid) {
        // TODO 校验后台用户
        TbBizPlaceMember member = placeMemberService.getPlaceMemberById(memberId);
        APIResponse result = placeMemberService.frozenMember(member); // 冻结会员
        if (null != result && result.isRet()){
            result = placeMemberService.logOffMemberCardByMember(member); // 注销会员卡
            // 添加日志
            businessLogService.insertIntoBusinessLog(memberId,PlaceConstants.LOG_TYPE_PLACE_MEMBER,adminUid,"冻结会员","冻结会员");
        }
        if (null != result && result.isRet()){
            return APIResponse.returnSuccess();
        } else {
            return APIResponse.returnFail("注销会员卡失败");
        }
    }

    //修改会员手机号
    @Override
    @Deprecated
    public APIResponse updatePlaceMemberInfo(ReqMemberCard reqMemberCard) {
        TbBizPlaceMember memberVo=new TbBizPlaceMember();
        memberVo.setMobile(reqMemberCard.getPhone());
        memberVo.setId(reqMemberCard.getMemberId());
        placeMemberService.updatePlaceMember(memberVo);
        //修改用户中心相应的手机号
        ReqChangePhone reqChangePhone=new ReqChangePhone();
        reqChangePhone.setPhone(reqMemberCard.getPhone());
        reqChangePhone.setType(2);
        reqChangePhone.setUid(reqMemberCard.getMemberUid());
        this.changePhone(reqChangePhone);
        // 添加日志
        businessLogService.insertIntoBusinessLog(reqMemberCard.getMemberId(),PlaceConstants.LOG_TYPE_PLACE_MEMBER,reqMemberCard.getUid(),"修改手机号","修改手机号");
        return APIResponse.returnSuccess();
    }

    /**
     * 修改场馆会员手机号
     * @param reqMemberCard
     * @return
     */
    public APIResponse updatePlaceMemberMobile(ReqMemberCard reqMemberCard) {
        if (null != reqMemberCard && null != reqMemberCard.getMemberId()){
            TbBizPlaceMember tbBizPlaceMember = placeMemberService.getPlaceMemberById(reqMemberCard.getMemberId());
            if (null != reqMemberCard.getPhone()){
                // 新手机号去用户中心查询
                if (reqMemberCard.getPhone().equals(tbBizPlaceMember.getMobile())){
                    APIResponse.returnFail("手机号没有变化");
                }
                APIResponse<RespUserInfoBase> respUserInfoBaseAPIResponse = userServiceFacade.queryUserInfoByPhone(reqMemberCard.getPhone());
                if(respUserInfoBaseAPIResponse.isRet() && null != respUserInfoBaseAPIResponse.getData()){
                    Integer uid = respUserInfoBaseAPIResponse.getData().getUid();
                    if (!placeMemberService.isExistsPlaceMember(uid)){
                        // tb_biz_place_member 表中不存在时，更新当前会员信息记录
                        tbBizPlaceMember.setMobile(reqMemberCard.getPhone());
                        tbBizPlaceMember.setUid(uid);
                        placeMemberService.updatePlaceMember(tbBizPlaceMember);
                    } else {
                        // TODO 已经存在对应uid的会员记录
                        TbBizPlaceMember placeMember = placeMemberService.getPlaceMemberByUid(uid);

                    }
                    List<TbBizPlaceMemberCard> tbBizPlaceMemberCards = placeMemberService.getTbBizPlaceMemberCardsByUid(tbBizPlaceMember.getUid());
                    if (null != tbBizPlaceMemberCards && tbBizPlaceMemberCards.size() > 0){
                        for (TbBizPlaceMemberCard card : tbBizPlaceMemberCards){
                            card.setMemberUid(uid);
                            placeMemberService.updatePlaceMemberCard(card);
                        }
                    }
                } else {
                    // 向用户中心发起修改手机号请求
                    ReqChangePhone reqChangePhone=new ReqChangePhone();
                    reqChangePhone.setPhone(reqMemberCard.getPhone());
                    reqChangePhone.setType(2);
                    reqChangePhone.setUid(reqMemberCard.getMemberUid());
                    this.changePhone(reqChangePhone);

                    // 更新本地会员手机号
                    tbBizPlaceMember.setMobile(reqMemberCard.getPhone());
                    placeMemberService.updatePlaceMember(tbBizPlaceMember);
                }
            }
            // 添加日志
            businessLogService.insertIntoBusinessLog(reqMemberCard.getMemberId(),
                    PlaceConstants.LOG_TYPE_PLACE_MEMBER,
                    reqMemberCard.getUid(),
                    "修改手机号",
                    "修改手机号:原手机号->" + tbBizPlaceMember.getMobile() + " 新手机号->" +reqMemberCard.getPhone());
        }
        return APIResponse.returnSuccess();
    }

    @Override
    public APIResponse<?> updateMemberTypeStatusById(Integer id, byte status) {
        APIResponse response = placeMemberService.updateMemberTypeStatusById(id, status);
        if (response.isRet()) {
            TbBizPlaceMemberCardType tbBizPlaceMemberCardType = tbBizPlaceMemberCardTypeMapper.selectByPrimaryKey(id);

            if (!StringUtils.isEmpty(tbBizPlaceMemberCardType)) {
                TbBizPlaceMemberCardTypeExample tbBizPlaceMemberCardTypeExample = new TbBizPlaceMemberCardTypeExample();
                tbBizPlaceMemberCardTypeExample.createCriteria()
                        .andPlaceIdEqualTo(tbBizPlaceMemberCardType.getPlaceId())
                        .andSourceTypeEqualTo(PlaceConstants.PLACE_MEMBER_CARD_TYPE_GENERAL_MEMBER)
                        .andStatusEqualTo(PlaceConstants.PLACE_MEMBER_CARD_STATUS_NORMAL)
                        .andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
                List<TbBizPlaceMemberCardType> tbBizPlaceMemberCardTypes =
                        tbBizPlaceMemberCardTypeMapper.selectByExample(tbBizPlaceMemberCardTypeExample);
                boolean flag = false;
                TbBizPlaceAttach placeAttach = placeBaseService.getBizPlaceAttach(tbBizPlaceMemberCardType.getPlaceId());

                if (CollectionUtils.isNotEmpty(tbBizPlaceMemberCardTypes)){
                    if (tbBizPlaceMemberCardType.getIsDelete() == Constants.IS_DELETE_FALSE) {
                        if (placeAttach != null) {
                            if (null == placeAttach.getIsVip() || Constants.BYTE_ZERO == placeAttach.getIsVip()) {
                                placeAttach.setIsVip(Constants.BYTE_ONE); // 支持办理会员卡
                                flag = true;
                            }
                        }
                    }
                } else {
                    if (placeAttach != null) {
                        if (Constants.BYTE_ONE == placeAttach.getIsVip()) {
                            placeAttach.setIsVip(Constants.BYTE_ZERO); // 不支持办理会员卡
                            flag = true;
                        }
                    }
                }
                if (flag) {
                    placeBaseService.updatePlaceAttachBySelective(placeAttach);
                    //是否支持会员存放到redis
                    String placeIdKey = PlaceConstants.CACHE_PLACE_ATTACH_INFO_PREFIX+String.valueOf(placeAttach.getPlaceId());
                    placeRedisTemplate.set(placeIdKey,placeAttach,PlaceConstants.PLACE_INFO_CACHE_TIME);
                    searchService.addPlaceSaleIndex(tbBizPlaceMemberCardType.getPlaceId());
                }
            }
        }
        return response;
    }

    /**
     * 设置两个场馆会员共享
     * @param placeId
     * @param relatePlaceId
     * @return
     */
    @Override
    @Transactional
    public APIResponse setPlaceShareMember(Integer placeId, Integer relatePlaceId) {
        TbBizPlaceAttach placeAttach = placeBaseService.getBizPlaceAttach(placeId);
        TbBizPlaceAttach relatePlaceAttach = placeBaseService.getBizPlaceAttach(relatePlaceId);
        if (null == placeAttach || null == relatePlaceAttach){
            return APIResponse.returnFail("场馆附属信息没有维护");
        }
        String vipShareNo = getVipShareNo(placeAttach, relatePlaceAttach);
        List<Integer> placeIds = getAllPlaceIdsForShareMember(placeAttach.getVipShareNo(), relatePlaceAttach.getVipShareNo());
        placeIds.add(placeId);
        placeIds.add(relatePlaceId);
        placeMemberService.updatePlaceAttachBatch(vipShareNo, placeIds);
        // Todo 增加操作日志
        return APIResponse.returnSuccess();
    }

    private List<Integer> getAllPlaceIdsForShareMember(String firstVipNo, String secondVipNo) {
        List<Integer> placeIds = new ArrayList<Integer>();
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(firstVipNo)){
            List<Integer> firstPlaceIds = placeMemberService.getSharePlaceIdsByVipShareNo(firstVipNo);
            if (null != firstPlaceIds && firstPlaceIds.size() > 0){
                placeIds.addAll(firstPlaceIds);
            }
        }
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(firstVipNo)){
            List<Integer> secondPlaceIds = placeMemberService.getSharePlaceIdsByVipShareNo(secondVipNo);
            if (null != secondPlaceIds && secondPlaceIds.size() > 0){
                placeIds.addAll(secondPlaceIds);
            }
        }
        return placeIds;
    }

    /**
     * 生成关联后的vipShareNo
     * @param placeAttach
     * @param relatePlaceAttach
     * @return
     */
    private String getVipShareNo(TbBizPlaceAttach placeAttach, TbBizPlaceAttach relatePlaceAttach) {
        if (null != placeAttach && null != relatePlaceAttach){
            if (org.apache.commons.lang3.StringUtils.isNotEmpty(placeAttach.getVipShareNo())){
                return placeAttach.getVipShareNo();
            }
            if (org.apache.commons.lang3.StringUtils.isNotEmpty(relatePlaceAttach.getVipShareNo())){
                return relatePlaceAttach.getVipShareNo();
            }
            return UUIDUtils.createId();
        }
        return null;
    }


    /**
     *  根据placeId查询互通会员场馆
     * @param placeId
     * @return
     */
    @Override
    public APIResponse getSharePlace(Integer placeId) {
        TbBizPlaceAttach placeAttach = placeBaseService.getBizPlaceAttach(placeId);
        List<RespPlaceInfo> placeList = new ArrayList<RespPlaceInfo>();
        if (null != placeAttach && !StringUtils.isEmpty(placeAttach.getVipShareNo())){
            placeList = placeBaseService.getSharePlace(placeId, placeAttach.getVipShareNo());
        }
        return APIResponse.returnSuccess(placeList);
    }

    /**
     * 解除场馆共享会员
     * @param relatePlaceId
     * @return
     */
    @Override
    public APIResponse cancelPlaceShareMember(Integer relatePlaceId) {
        TbBizPlaceAttach placeAttach = placeBaseService.getBizPlaceAttach(relatePlaceId);
        if (null != placeAttach){
            placeAttach.setIsVipShare(Constants.NO);
            String vipShareNo = placeAttach.getVipShareNo();
            placeAttach.setVipShareNo("");
            placeBaseService.updatePlaceAttachBySelective(placeAttach);
            /**解除剩余最后一个场馆**/
            if(!StringUtils.isEmpty(vipShareNo)){
                List<TbBizPlaceAttach> tbBizPlaceAttaches =  placeBaseService.getBizPlaceAttachList(vipShareNo);
                if (null != tbBizPlaceAttaches && tbBizPlaceAttaches.size()==1){
                    TbBizPlaceAttach placeAttach1 =  tbBizPlaceAttaches.get(0);
                    placeAttach1.setIsVipShare(Constants.NO);
                    placeAttach1.setVipShareNo("");
                    placeBaseService.updatePlaceAttachBySelective(placeAttach1);
                }
            }
        }
        return APIResponse.returnSuccess();
    }

    /**
     * 查询会员类型列表
     * @param placeMemberTypeVo
     * @return
     */
    @Override
    public APIResponse queryMemberTypeListByConditions(PlaceMemberTypeVo placeMemberTypeVo) {
        placeMemberTypeVo.setSearchType(Constants.BYTE_ONE); // 普通场馆场馆搜索
        // 通馆会员共享业务特殊处理
        if (null != placeMemberTypeVo &&  null != placeMemberTypeVo.getPlaceId()){
            TbBizPlaceAttach placeAttach = placeBaseService.getBizPlaceAttach(placeMemberTypeVo.getPlaceId());
            if (null != placeAttach && org.apache.commons.lang3.StringUtils.isNotEmpty(placeAttach.getVipShareNo())){
                String vipShareNo = placeAttach.getVipShareNo();
                List<TbBizPlaceAttach> placeAttachList = placeBaseService.getSharePlaceVipByShareNo(vipShareNo);
                String placeIdStr = packagePlaceIdStr(placeAttachList);
                if (org.apache.commons.lang3.StringUtils.isNotEmpty(placeIdStr)){
                    placeMemberTypeVo.setPlaceIdStr(placeIdStr);
                    placeMemberTypeVo.setSearchType(Constants.BYTE_TWO); // 共享会员场馆搜索
                }
            }
        }
        return placeMemberService.queryMemberTypeListByConditions(placeMemberTypeVo);
    }

    /**
     * 会员卡类型详情
     * @param cardTypeId
     * @return
     */
    @Override
    public APIResponse<?> getPlaceMemberCardType(Integer placeId, Integer cardTypeId) {
        TbBizPlaceMemberCardType cardType = placeMemberService.getMemberTypeById(cardTypeId);
        RespMemberCardType retCardType = new RespMemberCardType();

        assembleRespMemberCard(placeId, cardType, retCardType);
        return APIResponse.returnSuccess(retCardType);
    }

    @Async
    public void changePhone(ReqChangePhone reqChangePhone){
        try{
            APIResponse result=userServiceFacade.changePhone(reqChangePhone);
            if (result.getErrcode()==200 && result.isRet()){
                logger.warn("修改成功！");
            }else{
                logger.info("修改失败！----》"+JSON.toJSONString(result));
            }
        }catch(Exception e){
            logger.info("修改失败!----->"+e.getMessage());
        }

    }

}
